@@ -0,0 +1,321 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +package api_test |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + "context" |
| 8 | + "encoding/json" |
| 9 | + "net/http" |
| 10 | + "net/http/httptest" |
| 11 | + "os" |
| 12 | + "path/filepath" |
| 13 | + "strings" |
| 14 | + "testing" |
| 15 | + |
| 16 | + "github.com/jackc/pgx/v5/pgxpool" |
| 17 | + |
| 18 | + "github.com/tenseleyFlow/shithub/internal/auth/pat" |
| 19 | + "github.com/tenseleyFlow/shithub/internal/testing/dbtest" |
| 20 | + usersdb "github.com/tenseleyFlow/shithub/internal/users/sqlc" |
| 21 | +) |
| 22 | + |
| 23 | +type apiUserKey struct { |
| 24 | + ID int64 `json:"id"` |
| 25 | + Title string `json:"title"` |
| 26 | + Key string `json:"key"` |
| 27 | + Fingerprint string `json:"fingerprint"` |
| 28 | + KeyType string `json:"key_type"` |
| 29 | + Verified bool `json:"verified"` |
| 30 | + ReadOnly bool `json:"read_only"` |
| 31 | + CreatedAt string `json:"created_at"` |
| 32 | +} |
| 33 | + |
| 34 | +func loadKeyFixture(t *testing.T, name string) string { |
| 35 | + t.Helper() |
| 36 | + path := filepath.Join("..", "..", "..", "auth", "sshkey", "testdata", name) |
| 37 | + b, err := os.ReadFile(path) |
| 38 | + if err != nil { |
| 39 | + t.Fatalf("read fixture %s: %v", path, err) |
| 40 | + } |
| 41 | + return strings.TrimSpace(string(b)) |
| 42 | +} |
| 43 | + |
| 44 | +func seedSigningKey(t *testing.T, pool *pgxpool.Pool, userID int64, fingerprint string) int64 { |
| 45 | + t.Helper() |
| 46 | + k, err := usersdb.New().InsertUserSSHKey(context.Background(), pool, usersdb.InsertUserSSHKeyParams{ |
| 47 | + UserID: userID, |
| 48 | + Title: "signing-only", |
| 49 | + FingerprintSha256: fingerprint, |
| 50 | + KeyType: "ssh-ed25519", |
| 51 | + KeyBits: 0, |
| 52 | + PublicKey: "ssh-ed25519 AAAA…signing test", |
| 53 | + Kind: "signing", |
| 54 | + }) |
| 55 | + if err != nil { |
| 56 | + t.Fatalf("seed signing key: %v", err) |
| 57 | + } |
| 58 | + return k.ID |
| 59 | +} |
| 60 | + |
| 61 | +func TestUserKeys_CreateListGetDelete(t *testing.T) { |
| 62 | + pool := dbtest.NewTestDB(t) |
| 63 | + router := newCrossCuttingAPIRouter(t, pool) |
| 64 | + userID := crossCuttingUser(t, pool) |
| 65 | + tokenWrite := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserWrite)) |
| 66 | + tokenRead := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserRead)) |
| 67 | + pubBlob := loadKeyFixture(t, "ed25519.pub") |
| 68 | + |
| 69 | + // Create. |
| 70 | + body, _ := json.Marshal(map[string]string{"title": "laptop", "key": pubBlob}) |
| 71 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 72 | + req.Header.Set("Authorization", "Bearer "+tokenWrite) |
| 73 | + req.Header.Set("Content-Type", "application/json") |
| 74 | + rr := httptest.NewRecorder() |
| 75 | + router.ServeHTTP(rr, req) |
| 76 | + if rr.Code != http.StatusCreated { |
| 77 | + t.Fatalf("create status: got %d, want 201; body=%s", rr.Code, rr.Body.String()) |
| 78 | + } |
| 79 | + var created apiUserKey |
| 80 | + if err := json.Unmarshal(rr.Body.Bytes(), &created); err != nil { |
| 81 | + t.Fatalf("decode create: %v; body=%s", err, rr.Body.String()) |
| 82 | + } |
| 83 | + if created.ID == 0 || created.Title != "laptop" || created.KeyType != "ssh-ed25519" { |
| 84 | + t.Errorf("created shape unexpected: %+v", created) |
| 85 | + } |
| 86 | + if !strings.HasPrefix(created.Fingerprint, "SHA256:") { |
| 87 | + t.Errorf("fingerprint not prefixed: %q", created.Fingerprint) |
| 88 | + } |
| 89 | + |
| 90 | + // List. |
| 91 | + req = httptest.NewRequest(http.MethodGet, "/api/v1/user/keys", nil) |
| 92 | + req.Header.Set("Authorization", "Bearer "+tokenRead) |
| 93 | + rr = httptest.NewRecorder() |
| 94 | + router.ServeHTTP(rr, req) |
| 95 | + if rr.Code != http.StatusOK { |
| 96 | + t.Fatalf("list status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) |
| 97 | + } |
| 98 | + var listed []apiUserKey |
| 99 | + if err := json.Unmarshal(rr.Body.Bytes(), &listed); err != nil { |
| 100 | + t.Fatalf("decode list: %v", err) |
| 101 | + } |
| 102 | + if len(listed) != 1 || listed[0].ID != created.ID { |
| 103 | + t.Errorf("list shape unexpected: %+v", listed) |
| 104 | + } |
| 105 | + |
| 106 | + // Get by id. |
| 107 | + req = httptest.NewRequest(http.MethodGet, "/api/v1/user/keys/"+itoa(created.ID), nil) |
| 108 | + req.Header.Set("Authorization", "Bearer "+tokenRead) |
| 109 | + rr = httptest.NewRecorder() |
| 110 | + router.ServeHTTP(rr, req) |
| 111 | + if rr.Code != http.StatusOK { |
| 112 | + t.Fatalf("get status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) |
| 113 | + } |
| 114 | + |
| 115 | + // Delete. |
| 116 | + req = httptest.NewRequest(http.MethodDelete, "/api/v1/user/keys/"+itoa(created.ID), nil) |
| 117 | + req.Header.Set("Authorization", "Bearer "+tokenWrite) |
| 118 | + rr = httptest.NewRecorder() |
| 119 | + router.ServeHTTP(rr, req) |
| 120 | + if rr.Code != http.StatusNoContent { |
| 121 | + t.Fatalf("delete status: got %d, want 204; body=%s", rr.Code, rr.Body.String()) |
| 122 | + } |
| 123 | + |
| 124 | + // Subsequent get returns 404. |
| 125 | + req = httptest.NewRequest(http.MethodGet, "/api/v1/user/keys/"+itoa(created.ID), nil) |
| 126 | + req.Header.Set("Authorization", "Bearer "+tokenRead) |
| 127 | + rr = httptest.NewRecorder() |
| 128 | + router.ServeHTTP(rr, req) |
| 129 | + if rr.Code != http.StatusNotFound { |
| 130 | + t.Fatalf("post-delete get: got %d, want 404; body=%s", rr.Code, rr.Body.String()) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +func TestUserKeys_CreateRejectsBadKey(t *testing.T) { |
| 135 | + pool := dbtest.NewTestDB(t) |
| 136 | + router := newCrossCuttingAPIRouter(t, pool) |
| 137 | + userID := crossCuttingUser(t, pool) |
| 138 | + token := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserWrite)) |
| 139 | + |
| 140 | + body, _ := json.Marshal(map[string]string{"title": "broken", "key": "not even close to a key"}) |
| 141 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 142 | + req.Header.Set("Authorization", "Bearer "+token) |
| 143 | + req.Header.Set("Content-Type", "application/json") |
| 144 | + rr := httptest.NewRecorder() |
| 145 | + router.ServeHTTP(rr, req) |
| 146 | + |
| 147 | + if rr.Code != http.StatusUnprocessableEntity { |
| 148 | + t.Fatalf("status: got %d, want 422; body=%s", rr.Code, rr.Body.String()) |
| 149 | + } |
| 150 | + var envelope struct { |
| 151 | + Error string `json:"error"` |
| 152 | + } |
| 153 | + if err := json.Unmarshal(rr.Body.Bytes(), &envelope); err != nil { |
| 154 | + t.Fatalf("decode envelope: %v", err) |
| 155 | + } |
| 156 | + if envelope.Error == "" { |
| 157 | + t.Errorf("error envelope empty: %s", rr.Body.String()) |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +func TestUserKeys_CreateRejectsRSA1024(t *testing.T) { |
| 162 | + pool := dbtest.NewTestDB(t) |
| 163 | + router := newCrossCuttingAPIRouter(t, pool) |
| 164 | + userID := crossCuttingUser(t, pool) |
| 165 | + token := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserWrite)) |
| 166 | + |
| 167 | + body, _ := json.Marshal(map[string]string{"title": "weak", "key": loadKeyFixture(t, "rsa1024.pub")}) |
| 168 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 169 | + req.Header.Set("Authorization", "Bearer "+token) |
| 170 | + rr := httptest.NewRecorder() |
| 171 | + router.ServeHTTP(rr, req) |
| 172 | + |
| 173 | + if rr.Code != http.StatusUnprocessableEntity { |
| 174 | + t.Fatalf("status: got %d, want 422; body=%s", rr.Code, rr.Body.String()) |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +func TestUserKeys_CreateRequiresUserWriteScope(t *testing.T) { |
| 179 | + pool := dbtest.NewTestDB(t) |
| 180 | + router := newCrossCuttingAPIRouter(t, pool) |
| 181 | + userID := crossCuttingUser(t, pool) |
| 182 | + token := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserRead)) |
| 183 | + pubBlob := loadKeyFixture(t, "ed25519.pub") |
| 184 | + |
| 185 | + body, _ := json.Marshal(map[string]string{"title": "laptop", "key": pubBlob}) |
| 186 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 187 | + req.Header.Set("Authorization", "Bearer "+token) |
| 188 | + rr := httptest.NewRecorder() |
| 189 | + router.ServeHTTP(rr, req) |
| 190 | + |
| 191 | + if rr.Code != http.StatusForbidden { |
| 192 | + t.Fatalf("status: got %d, want 403; body=%s", rr.Code, rr.Body.String()) |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +func TestUserKeys_GetUnknownReturns404(t *testing.T) { |
| 197 | + pool := dbtest.NewTestDB(t) |
| 198 | + router := newCrossCuttingAPIRouter(t, pool) |
| 199 | + userID := crossCuttingUser(t, pool) |
| 200 | + token := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserRead)) |
| 201 | + |
| 202 | + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/keys/9999999", nil) |
| 203 | + req.Header.Set("Authorization", "Bearer "+token) |
| 204 | + rr := httptest.NewRecorder() |
| 205 | + router.ServeHTTP(rr, req) |
| 206 | + if rr.Code != http.StatusNotFound { |
| 207 | + t.Fatalf("status: got %d, want 404; body=%s", rr.Code, rr.Body.String()) |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +func TestUserKeys_ListExcludesSigningKeys(t *testing.T) { |
| 212 | + pool := dbtest.NewTestDB(t) |
| 213 | + router := newCrossCuttingAPIRouter(t, pool) |
| 214 | + userID := crossCuttingUser(t, pool) |
| 215 | + tokenWrite := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserWrite)) |
| 216 | + tokenRead := mintRunnerAPIPAT(t, pool, userID, string(pat.ScopeUserRead)) |
| 217 | + |
| 218 | + // Add an authentication key via REST. |
| 219 | + pubBlob := loadKeyFixture(t, "ed25519.pub") |
| 220 | + body, _ := json.Marshal(map[string]string{"title": "laptop", "key": pubBlob}) |
| 221 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 222 | + req.Header.Set("Authorization", "Bearer "+tokenWrite) |
| 223 | + rr := httptest.NewRecorder() |
| 224 | + router.ServeHTTP(rr, req) |
| 225 | + if rr.Code != http.StatusCreated { |
| 226 | + t.Fatalf("seed auth key: %d; body=%s", rr.Code, rr.Body.String()) |
| 227 | + } |
| 228 | + |
| 229 | + // Seed a signing key directly. |
| 230 | + signingID := seedSigningKey(t, pool, userID, "z9R6V9d8aGAxN1pVdQF/notarealfingerprint=") |
| 231 | + |
| 232 | + // List should return only the authentication one. |
| 233 | + req = httptest.NewRequest(http.MethodGet, "/api/v1/user/keys", nil) |
| 234 | + req.Header.Set("Authorization", "Bearer "+tokenRead) |
| 235 | + rr = httptest.NewRecorder() |
| 236 | + router.ServeHTTP(rr, req) |
| 237 | + if rr.Code != http.StatusOK { |
| 238 | + t.Fatalf("list status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) |
| 239 | + } |
| 240 | + var listed []apiUserKey |
| 241 | + if err := json.Unmarshal(rr.Body.Bytes(), &listed); err != nil { |
| 242 | + t.Fatalf("decode list: %v", err) |
| 243 | + } |
| 244 | + for _, k := range listed { |
| 245 | + if k.ID == signingID { |
| 246 | + t.Errorf("signing key leaked into auth-keys list: %+v", k) |
| 247 | + } |
| 248 | + } |
| 249 | + |
| 250 | + // Direct GET of the signing key by id should also 404 on this surface. |
| 251 | + req = httptest.NewRequest(http.MethodGet, "/api/v1/user/keys/"+itoa(signingID), nil) |
| 252 | + req.Header.Set("Authorization", "Bearer "+tokenRead) |
| 253 | + rr = httptest.NewRecorder() |
| 254 | + router.ServeHTTP(rr, req) |
| 255 | + if rr.Code != http.StatusNotFound { |
| 256 | + t.Fatalf("signing key direct get: got %d, want 404; body=%s", rr.Code, rr.Body.String()) |
| 257 | + } |
| 258 | +} |
| 259 | + |
| 260 | +func TestUserKeys_DeleteOnlyOwnersKey(t *testing.T) { |
| 261 | + pool := dbtest.NewTestDB(t) |
| 262 | + router := newCrossCuttingAPIRouter(t, pool) |
| 263 | + |
| 264 | + // User A creates a key. |
| 265 | + userA := crossCuttingUser(t, pool) |
| 266 | + tokenA := mintRunnerAPIPAT(t, pool, userA, string(pat.ScopeUserWrite)) |
| 267 | + pubBlob := loadKeyFixture(t, "ed25519.pub") |
| 268 | + body, _ := json.Marshal(map[string]string{"title": "laptop", "key": pubBlob}) |
| 269 | + req := httptest.NewRequest(http.MethodPost, "/api/v1/user/keys", bytes.NewReader(body)) |
| 270 | + req.Header.Set("Authorization", "Bearer "+tokenA) |
| 271 | + rr := httptest.NewRecorder() |
| 272 | + router.ServeHTTP(rr, req) |
| 273 | + if rr.Code != http.StatusCreated { |
| 274 | + t.Fatalf("A create: %d; %s", rr.Code, rr.Body.String()) |
| 275 | + } |
| 276 | + var created apiUserKey |
| 277 | + if err := json.Unmarshal(rr.Body.Bytes(), &created); err != nil { |
| 278 | + t.Fatalf("decode: %v", err) |
| 279 | + } |
| 280 | + |
| 281 | + // User B tries to delete user A's key. |
| 282 | + userB, err := usersdb.New().CreateUser(context.Background(), pool, usersdb.CreateUserParams{ |
| 283 | + Username: "bob", |
| 284 | + DisplayName: "Bob", |
| 285 | + PasswordHash: runnerAPIFixtureHash, |
| 286 | + }) |
| 287 | + if err != nil { |
| 288 | + t.Fatalf("create userB: %v", err) |
| 289 | + } |
| 290 | + tokenB := mintRunnerAPIPAT(t, pool, userB.ID, string(pat.ScopeUserWrite)) |
| 291 | + req = httptest.NewRequest(http.MethodDelete, "/api/v1/user/keys/"+itoa(created.ID), nil) |
| 292 | + req.Header.Set("Authorization", "Bearer "+tokenB) |
| 293 | + rr = httptest.NewRecorder() |
| 294 | + router.ServeHTTP(rr, req) |
| 295 | + if rr.Code != http.StatusNotFound { |
| 296 | + t.Fatalf("cross-user delete: got %d, want 404; body=%s", rr.Code, rr.Body.String()) |
| 297 | + } |
| 298 | +} |
| 299 | + |
| 300 | +func itoa(i int64) string { |
| 301 | + const digits = "0123456789" |
| 302 | + if i == 0 { |
| 303 | + return "0" |
| 304 | + } |
| 305 | + neg := i < 0 |
| 306 | + if neg { |
| 307 | + i = -i |
| 308 | + } |
| 309 | + var buf [20]byte |
| 310 | + pos := len(buf) |
| 311 | + for i > 0 { |
| 312 | + pos-- |
| 313 | + buf[pos] = digits[i%10] |
| 314 | + i /= 10 |
| 315 | + } |
| 316 | + if neg { |
| 317 | + pos-- |
| 318 | + buf[pos] = '-' |
| 319 | + } |
| 320 | + return string(buf[pos:]) |
| 321 | +} |