github.com/google/go-github/v50@v50.2.0/github/orgs_audit_log_test.go (about)

     1  // Copyright 2021 The go-github AUTHORS. All rights reserved.
     2  //
     3  // `Use` of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package github
     7  
     8  import (
     9  	"context"
    10  	"fmt"
    11  	"net/http"
    12  	"strings"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/google/go-cmp/cmp"
    17  )
    18  
    19  func TestOrganizationService_GetAuditLog(t *testing.T) {
    20  	client, mux, _, teardown := setup()
    21  	defer teardown()
    22  
    23  	mux.HandleFunc("/orgs/o/audit-log", func(w http.ResponseWriter, r *http.Request) {
    24  		testMethod(t, r, "GET")
    25  
    26  		fmt.Fprint(w, `[
    27  		{
    28          "active": true,
    29          "workflow_id": 123456,
    30          "head_branch": "master",
    31          "org": "o",
    32          "trigger_id": null,
    33          "repo": "o/blue-crayon-1",
    34          "created_at": 1615077308538,
    35          "head_sha": "5acdeadbeef64d1a62388e901e5cdc9358644b37",
    36          "conclusion": "success",
    37          "old_permission": "read",
    38          "permission": "admin",
    39          "actor": "testactor",
    40          "completed_at": "2021-03-07T00:35:08.000Z",
    41          "@timestamp": 1615077308538,
    42          "name": "Code scanning - action",
    43          "action": "workflows.completed_workflow_run",
    44          "started_at": "2021-03-07T00:33:04.000Z",
    45          "event": "schedule",
    46          "workflow_run_id": 628312345,
    47          "_document_id": "beeZYapIUe-wKg5-beadb33",
    48          "config": {
    49              "content_type": "json",
    50              "insecure_ssl": "0",
    51              "url": "https://example.com/deadbeef-new-hook"
    52           },
    53          "events": ["code_scanning_alert"]
    54  		}]`)
    55  	})
    56  	ctx := context.Background()
    57  	getOpts := GetAuditLogOptions{
    58  		Include: String("all"),
    59  		Phrase:  String("action:workflows"),
    60  		Order:   String("asc"),
    61  	}
    62  
    63  	auditEntries, resp, err := client.Organizations.GetAuditLog(ctx, "o", &getOpts)
    64  	if err != nil {
    65  		t.Errorf("Organizations.GetAuditLog returned error: %v", err)
    66  	}
    67  	startedAt, _ := time.Parse(time.RFC3339, "2021-03-07T00:33:04.000Z")
    68  	completedAt, _ := time.Parse(time.RFC3339, "2021-03-07T00:35:08.000Z")
    69  	timestamp := time.Unix(0, 1615077308538*1e6)
    70  
    71  	want := []*AuditEntry{
    72  		{
    73  			Timestamp:     &Timestamp{timestamp},
    74  			DocumentID:    String("beeZYapIUe-wKg5-beadb33"),
    75  			Action:        String("workflows.completed_workflow_run"),
    76  			Actor:         String("testactor"),
    77  			Active:        Bool(true),
    78  			CompletedAt:   &Timestamp{completedAt},
    79  			Conclusion:    String("success"),
    80  			CreatedAt:     &Timestamp{timestamp},
    81  			Event:         String("schedule"),
    82  			HeadBranch:    String("master"),
    83  			HeadSHA:       String("5acdeadbeef64d1a62388e901e5cdc9358644b37"),
    84  			Name:          String("Code scanning - action"),
    85  			OldPermission: String("read"),
    86  			Org:           String("o"),
    87  			Permission:    String("admin"),
    88  			Repo:          String("o/blue-crayon-1"),
    89  			StartedAt:     &Timestamp{startedAt},
    90  			WorkflowID:    Int64(123456),
    91  			WorkflowRunID: Int64(628312345),
    92  			Events:        []string{"code_scanning_alert"},
    93  			Config: &HookConfig{
    94  				ContentType: String("json"),
    95  				InsecureSSL: String("0"),
    96  				URL:         String("https://example.com/deadbeef-new-hook"),
    97  			},
    98  		},
    99  	}
   100  
   101  	if !cmp.Equal(auditEntries, want) {
   102  		t.Errorf("Organizations.GetAuditLog return \ngot: %+v,\nwant:%+v", auditEntries, want)
   103  	}
   104  
   105  	// assert query string has lower case params
   106  	requestedQuery := resp.Request.URL.RawQuery
   107  	if !strings.Contains(requestedQuery, "phrase") {
   108  		t.Errorf("Organizations.GetAuditLog query string \ngot: %+v,\nwant:%+v", requestedQuery, "phrase")
   109  	}
   110  
   111  	const methodName = "GetAuditLog"
   112  	testBadOptions(t, methodName, func() (err error) {
   113  		_, _, err = client.Organizations.GetAuditLog(ctx, "\n", &getOpts)
   114  		return err
   115  	})
   116  
   117  	testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
   118  		got, resp, err := client.Organizations.GetAuditLog(ctx, "o", &GetAuditLogOptions{})
   119  		if got != nil {
   120  			t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
   121  		}
   122  		return resp, err
   123  	})
   124  }
   125  
   126  func TestGetAuditLogOptions_Marshal(t *testing.T) {
   127  	testJSONMarshal(t, &GetAuditLogOptions{}, "{}")
   128  
   129  	u := &GetAuditLogOptions{
   130  		Phrase:  String("p"),
   131  		Include: String("i"),
   132  		Order:   String("o"),
   133  		ListCursorOptions: ListCursorOptions{
   134  			Page:    "p",
   135  			PerPage: 1,
   136  			After:   "a",
   137  			Before:  "b",
   138  		},
   139  	}
   140  
   141  	want := `{
   142  		"phrase": "p",
   143  		"include": "i",
   144  		"order": "o",
   145  		"Page": "p",
   146  		"PerPage": 1,
   147  		"After": "a",
   148  		"Before": "b"
   149  	}`
   150  
   151  	testJSONMarshal(t, u, want)
   152  }
   153  
   154  func TestHookConfig_Marshal(t *testing.T) {
   155  	testJSONMarshal(t, &HookConfig{}, "{}")
   156  
   157  	u := &HookConfig{
   158  		ContentType: String("ct"),
   159  		InsecureSSL: String("ct"),
   160  		URL:         String("url"),
   161  	}
   162  
   163  	want := `{
   164  		"content_type": "ct",
   165  		"insecure_ssl": "ct",
   166  		"url": "url"
   167  	}`
   168  
   169  	testJSONMarshal(t, u, want)
   170  }
   171  
   172  func TestAuditEntry_Marshal(t *testing.T) {
   173  	testJSONMarshal(t, &AuditEntry{}, "{}")
   174  
   175  	u := &AuditEntry{
   176  		Action:                String("a"),
   177  		Active:                Bool(false),
   178  		ActiveWas:             Bool(false),
   179  		Actor:                 String("ac"),
   180  		BlockedUser:           String("bu"),
   181  		Business:              String("b"),
   182  		CancelledAt:           &Timestamp{referenceTime},
   183  		CompletedAt:           &Timestamp{referenceTime},
   184  		Conclusion:            String("c"),
   185  		Config:                &HookConfig{URL: String("s")},
   186  		ConfigWas:             &HookConfig{URL: String("s")},
   187  		ContentType:           String("ct"),
   188  		CreatedAt:             &Timestamp{referenceTime},
   189  		DeployKeyFingerprint:  String("dkf"),
   190  		DocumentID:            String("did"),
   191  		Emoji:                 String("e"),
   192  		EnvironmentName:       String("en"),
   193  		Event:                 String("e"),
   194  		Events:                []string{"s"},
   195  		EventsWere:            []string{"s"},
   196  		Explanation:           String("e"),
   197  		Fingerprint:           String("f"),
   198  		HeadBranch:            String("hb"),
   199  		HeadSHA:               String("hsha"),
   200  		HookID:                Int64(1),
   201  		IsHostedRunner:        Bool(false),
   202  		JobName:               String("jn"),
   203  		LimitedAvailability:   Bool(false),
   204  		Message:               String("m"),
   205  		Name:                  String("n"),
   206  		OldPermission:         String("op"),
   207  		OldUser:               String("ou"),
   208  		OpenSSHPublicKey:      String("osshpk"),
   209  		Org:                   String("o"),
   210  		Permission:            String("p"),
   211  		PreviousVisibility:    String("pv"),
   212  		ReadOnly:              String("ro"),
   213  		Repo:                  String("r"),
   214  		Repository:            String("repo"),
   215  		RepositoryPublic:      Bool(false),
   216  		RunAttempt:            Int64(1),
   217  		RunnerGroupID:         Int64(1),
   218  		RunnerGroupName:       String("rgn"),
   219  		RunnerID:              Int64(1),
   220  		RunnerLabels:          []string{"s"},
   221  		RunnerName:            String("rn"),
   222  		SecretsPassed:         []string{"s"},
   223  		SourceVersion:         String("sv"),
   224  		StartedAt:             &Timestamp{referenceTime},
   225  		TargetLogin:           String("tl"),
   226  		TargetVersion:         String("tv"),
   227  		Team:                  String("t"),
   228  		Timestamp:             &Timestamp{referenceTime},
   229  		TransportProtocolName: String("tpn"),
   230  		TransportProtocol:     Int(1),
   231  		TriggerID:             Int64(1),
   232  		User:                  String("u"),
   233  		Visibility:            String("v"),
   234  		WorkflowID:            Int64(1),
   235  		WorkflowRunID:         Int64(1),
   236  	}
   237  
   238  	want := `{
   239  		"action": "a",
   240  		"active": false,
   241  		"active_was": false,
   242  		"actor": "ac",
   243  		"blocked_user": "bu",
   244  		"business": "b",
   245  		"cancelled_at": ` + referenceTimeStr + `,
   246  		"completed_at": ` + referenceTimeStr + `,
   247  		"conclusion": "c",
   248  		"config": {
   249  			"url": "s"
   250  		},
   251  		"config_was": {
   252  			"url": "s"
   253  		},
   254  		"content_type": "ct",
   255  		"created_at": ` + referenceTimeStr + `,
   256  		"deploy_key_fingerprint": "dkf",
   257  		"_document_id": "did",
   258  		"emoji": "e",
   259  		"environment_name": "en",
   260  		"event": "e",
   261  		"events": [
   262  			"s"
   263  		],
   264  		"events_were": [
   265  			"s"
   266  		],
   267  		"explanation": "e",
   268  		"fingerprint": "f",
   269  		"head_branch": "hb",
   270  		"head_sha": "hsha",
   271  		"hook_id": 1,
   272  		"is_hosted_runner": false,
   273  		"job_name": "jn",
   274  		"limited_availability": false,
   275  		"message": "m",
   276  		"name": "n",
   277  		"old_permission": "op",
   278  		"old_user": "ou",
   279  		"openssh_public_key": "osshpk",
   280  		"org": "o",
   281  		"permission": "p",
   282  		"previous_visibility": "pv",
   283  		"read_only": "ro",
   284  		"repo": "r",
   285  		"repository": "repo",
   286  		"repository_public": false,
   287  		"run_attempt": 1,
   288  		"runner_group_id": 1,
   289  		"runner_group_name": "rgn",
   290  		"runner_id": 1,
   291  		"runner_labels": [
   292  			"s"
   293  		],
   294  		"runner_name": "rn",
   295  		"secrets_passed": [
   296  			"s"
   297  		],
   298  		"source_version": "sv",
   299  		"started_at": ` + referenceTimeStr + `,
   300  		"target_login": "tl",
   301  		"target_version": "tv",
   302  		"team": "t",
   303  		"@timestamp": ` + referenceTimeStr + `,
   304  		"transport_protocol_name": "tpn",
   305  		"transport_protocol": 1,
   306  		"trigger_id": 1,
   307  		"user": "u",
   308  		"visibility": "v",
   309  		"workflow_id": 1,
   310  		"workflow_run_id": 1
   311  	}`
   312  
   313  	testJSONMarshal(t, u, want)
   314  }