A community based topic aggregation platform built on atproto
1package oauth 2 3import ( 4 "encoding/base64" 5 "os" 6 "testing" 7) 8 9func TestGetEnvBase64OrPlain(t *testing.T) { 10 tests := []struct { 11 name string 12 envKey string 13 envValue string 14 want string 15 wantError bool 16 }{ 17 { 18 name: "plain JSON value", 19 envKey: "TEST_PLAIN_JSON", 20 envValue: `{"alg":"ES256","kty":"EC"}`, 21 want: `{"alg":"ES256","kty":"EC"}`, 22 wantError: false, 23 }, 24 { 25 name: "base64 encoded value", 26 envKey: "TEST_BASE64_JSON", 27 envValue: "base64:" + base64.StdEncoding.EncodeToString([]byte(`{"alg":"ES256","kty":"EC"}`)), 28 want: `{"alg":"ES256","kty":"EC"}`, 29 wantError: false, 30 }, 31 { 32 name: "empty value", 33 envKey: "TEST_EMPTY", 34 envValue: "", 35 want: "", 36 wantError: false, 37 }, 38 { 39 name: "invalid base64", 40 envKey: "TEST_INVALID_BASE64", 41 envValue: "base64:not-valid-base64!!!", 42 want: "", 43 wantError: true, 44 }, 45 { 46 name: "plain string with special chars", 47 envKey: "TEST_SPECIAL_CHARS", 48 envValue: "secret-with-dashes_and_underscores", 49 want: "secret-with-dashes_and_underscores", 50 wantError: false, 51 }, 52 { 53 name: "base64 encoded hex string", 54 envKey: "TEST_BASE64_HEX", 55 envValue: "base64:" + base64.StdEncoding.EncodeToString([]byte("f1132c01b1a625a865c6c455a75ee793")), 56 want: "f1132c01b1a625a865c6c455a75ee793", 57 wantError: false, 58 }, 59 } 60 61 for _, tt := range tests { 62 t.Run(tt.name, func(t *testing.T) { 63 // Set environment variable 64 if tt.envValue != "" { 65 os.Setenv(tt.envKey, tt.envValue) 66 defer os.Unsetenv(tt.envKey) 67 } 68 69 got, err := GetEnvBase64OrPlain(tt.envKey) 70 71 if (err != nil) != tt.wantError { 72 t.Errorf("GetEnvBase64OrPlain() error = %v, wantError %v", err, tt.wantError) 73 return 74 } 75 76 if got != tt.want { 77 t.Errorf("GetEnvBase64OrPlain() = %v, want %v", got, tt.want) 78 } 79 }) 80 } 81} 82 83func TestGetEnvBase64OrPlain_RealWorldJWK(t *testing.T) { 84 // Test with a real JWK (the one from .env.dev) 85 realJWK := `{"alg":"ES256","crv":"P-256","d":"9tCMceYSgyZfO5KYOCm3rWEhXLqq2l4LjP7-PJtJKyk","kid":"oauth-client-key","kty":"EC","use":"sig","x":"EOYWEgZ2d-smTO6jh0f-9B7YSFYdlrvlryjuXTCrOjE","y":"_FR2jBcWNxoJl5cd1eq9sYtAs33No9AVtd42UyyWYi4"}` 86 87 tests := []struct { 88 name string 89 envValue string 90 want string 91 }{ 92 { 93 name: "plain JWK", 94 envValue: realJWK, 95 want: realJWK, 96 }, 97 { 98 name: "base64 encoded JWK", 99 envValue: "base64:" + base64.StdEncoding.EncodeToString([]byte(realJWK)), 100 want: realJWK, 101 }, 102 } 103 104 for _, tt := range tests { 105 t.Run(tt.name, func(t *testing.T) { 106 os.Setenv("TEST_REAL_JWK", tt.envValue) 107 defer os.Unsetenv("TEST_REAL_JWK") 108 109 got, err := GetEnvBase64OrPlain("TEST_REAL_JWK") 110 if err != nil { 111 t.Fatalf("unexpected error: %v", err) 112 } 113 114 if got != tt.want { 115 t.Errorf("GetEnvBase64OrPlain() = %v, want %v", got, tt.want) 116 } 117 }) 118 } 119}