feat(gitea): list the users of a managed git instance
GET /api/v1/admin/users with a read:admin token in the Authorization header, paged until an empty page. Errors carry no body, URL or token. Refs: t81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7b9ae37be7
commit
f9ada789ea
2 files changed
+220
No files matched your search
@@ -0,0 +1,118 @@
|
||||
// Package gitea reads the user list of a Managed Git instance (t81): one
|
||||
// Gitea per customer, read with a token of scope read:admin.
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// pageLimit is the page size asked for; Gitea may cap it lower
|
||||
// (API.MAX_RESPONSE_ITEMS), so paging stops on an empty page, not a short one.
|
||||
const (
|
||||
pageLimit = 50
|
||||
maxPages = 2000 // 100,000 users: a guard against a server that never ends
|
||||
maxBody = 8 << 20
|
||||
)
|
||||
|
||||
// User is the part of Gitea's admin user record the count uses.
|
||||
type User struct {
|
||||
Login string `json:"login"`
|
||||
// LoginName is the user's name at its login source: for accounts that
|
||||
// sign in through the tenant's Keycloak client, the Keycloak user id
|
||||
// (sub). Local accounts (the CI bot) have none.
|
||||
LoginName string `json:"login_name"`
|
||||
LastLogin time.Time `json:"last_login"`
|
||||
}
|
||||
|
||||
// SignedIn reports whether the user has signed in at least once. Gitea
|
||||
// reports "never" as the Unix epoch (in the server's zone); the Go zero time
|
||||
// covers a missing field.
|
||||
func (u User) SignedIn() bool {
|
||||
return !u.LastLogin.IsZero() && u.LastLogin.Unix() > 0
|
||||
}
|
||||
|
||||
// Client calls Gitea instances. The zero value uses http.DefaultClient.
|
||||
type Client struct {
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func (c *Client) http() *http.Client {
|
||||
if c != nil && c.HTTP != nil {
|
||||
return c.HTTP
|
||||
}
|
||||
return http.DefaultClient
|
||||
}
|
||||
|
||||
// ErrStatus is an unexpected HTTP status from Gitea. Its message carries the
|
||||
// status only, never the response body.
|
||||
type ErrStatus struct{ Code int }
|
||||
|
||||
func (e *ErrStatus) Error() string { return "gitea: status " + strconv.Itoa(e.Code) }
|
||||
|
||||
// ListUsers returns every user of the instance at baseURL
|
||||
// (GET /api/v1/admin/users, paged). The token goes in the Authorization
|
||||
// header only, so it never appears in a URL or an error.
|
||||
func (c *Client) ListUsers(ctx context.Context, baseURL, token string) ([]User, error) {
|
||||
if token == "" {
|
||||
return nil, errors.New("gitea: no token")
|
||||
}
|
||||
base, err := url.Parse(strings.TrimRight(baseURL, "/") + "/api/v1/admin/users")
|
||||
if err != nil || base.Host == "" {
|
||||
return nil, errors.New("gitea: invalid instance url")
|
||||
}
|
||||
var out []User
|
||||
for page := 1; page <= maxPages; page++ {
|
||||
u := *base
|
||||
u.RawQuery = url.Values{"page": {strconv.Itoa(page)}, "limit": {strconv.Itoa(pageLimit)}}.Encode()
|
||||
users, err := c.page(ctx, u.String(), token)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("page %d: %w", page, err)
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
out = append(out, users...)
|
||||
}
|
||||
return nil, errors.New("gitea: too many pages")
|
||||
}
|
||||
|
||||
func (c *Client) page(ctx context.Context, u, token string) ([]User, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, errors.New("gitea: build request")
|
||||
}
|
||||
req.Header.Set("Authorization", "token "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.http().Do(req)
|
||||
if err != nil {
|
||||
// Not the *url.Error itself: it names the instance's URL, and the
|
||||
// report this ends up in should name the service id only.
|
||||
var ue *url.Error
|
||||
if errors.As(err, &ue) && ue.Timeout() {
|
||||
return nil, errors.New("gitea: request timed out")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, fmt.Errorf("gitea: %w", ctx.Err())
|
||||
}
|
||||
return nil, errors.New("gitea: request failed")
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxBody))
|
||||
return nil, &ErrStatus{Code: resp.StatusCode}
|
||||
}
|
||||
var users []User
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&users); err != nil {
|
||||
return nil, errors.New("gitea: response is not a user list")
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const token = "sentinel-gitea-token-0123456789"
|
||||
|
||||
func TestListUsers_pagesUntilEmpty(t *testing.T) {
|
||||
all := []map[string]any{}
|
||||
for i := range 7 {
|
||||
all = append(all, map[string]any{"login": "u" + strconv.Itoa(i), "login_name": "kc-" + strconv.Itoa(i), "last_login": "2026-11-16T10:00:00+01:00"})
|
||||
}
|
||||
var pages []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/sub/api/v1/admin/users" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "token "+token || strings.Contains(r.URL.RawQuery, token) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
||||
pages = append(pages, r.URL.Query().Get("page")+"/"+r.URL.Query().Get("limit"))
|
||||
// The server caps the page size at 3, below the limit asked for.
|
||||
lo, hi := (page-1)*3, page*3
|
||||
lo, hi = min(lo, len(all)), min(hi, len(all))
|
||||
_ = json.NewEncoder(w).Encode(all[lo:hi])
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
users, err := (&Client{}).ListUsers(context.Background(), srv.URL+"/sub/", token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(users) != 7 || users[6].LoginName != "kc-6" || !users[0].SignedIn() {
|
||||
t.Fatalf("users: %+v", users)
|
||||
}
|
||||
if strings.Join(pages, ",") != "1/50,2/50,3/50,4/50" {
|
||||
t.Fatalf("pages asked: %v", pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListUsers_errorsCarryNoBodyOrToken(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"message":"token ` + token + ` lacks read:admin"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
_, err := (&Client{}).ListUsers(context.Background(), srv.URL, token)
|
||||
if err == nil || err.Error() != "page 1: gitea: status 403" {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
|
||||
// Unreachable: no URL, no token in the message.
|
||||
srv.Close()
|
||||
_, err = (&Client{}).ListUsers(context.Background(), srv.URL, token)
|
||||
if err == nil || strings.Contains(err.Error(), token) || strings.Contains(err.Error(), "127.0.0.1") {
|
||||
t.Fatalf("unreachable err: %v", err)
|
||||
}
|
||||
|
||||
if _, err := (&Client{}).ListUsers(context.Background(), "https://git.k-00001.example", ""); err == nil {
|
||||
t.Fatal("no token: want an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListUsers_notAList(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"message":"x"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := (&Client{}).ListUsers(context.Background(), srv.URL, token); err == nil || !strings.Contains(err.Error(), "not a user list") {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUser_signedIn(t *testing.T) {
|
||||
var never []User
|
||||
if err := json.Unmarshal([]byte(`[
|
||||
{"login_name":"a","last_login":"1970-01-01T01:00:00+01:00"},
|
||||
{"login_name":"b","last_login":"0001-01-01T00:00:00Z"},
|
||||
{"login_name":"c"}
|
||||
]`), &never); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, u := range never {
|
||||
if u.SignedIn() {
|
||||
t.Errorf("%s: signed in", u.LoginName)
|
||||
}
|
||||
}
|
||||
if !(User{LastLogin: time.Date(2026, 11, 1, 8, 0, 0, 0, time.UTC)}).SignedIn() {
|
||||
t.Error("a real sign-in does not count")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user