|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/coreos/go-oidc/v3/oidc" |
| 6 | + "github.com/hashicorp/go-bexpr" |
| 7 | + "github.com/labstack/echo/v4" |
| 8 | + "github.com/tailscale/tailscale-client-go/tailscale" |
| 9 | + "log" |
| 10 | + "net/http" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | +) |
| 14 | + |
| 15 | +const BEARER_SCHEMA = "Bearer " |
| 16 | + |
| 17 | +type KeyResponse struct { |
| 18 | + Key string `json:"key"` |
| 19 | +} |
| 20 | + |
| 21 | +func start() error { |
| 22 | + ctx := context.Background() |
| 23 | + |
| 24 | + apiKey := os.Getenv("TS_API_KEY") |
| 25 | + tailnet := os.Getenv("TS_TAILNET") |
| 26 | + issuer := os.Getenv("TS_KEYS_ISSUER") |
| 27 | + tags := os.Getenv("TS_KEYS_TAGS") |
| 28 | + filter := os.Getenv("TS_KEYS_BEXPR") |
| 29 | + |
| 30 | + client, err := tailscale.NewClient(apiKey, tailnet) |
| 31 | + if err != nil { |
| 32 | + return err |
| 33 | + } |
| 34 | + |
| 35 | + provider, err := oidc.NewProvider(ctx, issuer) |
| 36 | + if err != nil { |
| 37 | + return err |
| 38 | + } |
| 39 | + |
| 40 | + verifier := provider.Verifier(&oidc.Config{SkipClientIDCheck: true}) |
| 41 | + |
| 42 | + evaluator, err := bexpr.CreateEvaluator(filter) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + |
| 47 | + expirySeconds := uint64(300) |
| 48 | + capabilities := tailscale.KeyCapabilities{} |
| 49 | + capabilities.Devices.Create.Reusable = false |
| 50 | + capabilities.Devices.Create.Ephemeral = true |
| 51 | + if len(tags) != 0 { |
| 52 | + capabilities.Devices.Create.Tags = strings.Split(tags, ",") |
| 53 | + } |
| 54 | + |
| 55 | + e := echo.New() |
| 56 | + e.HideBanner = true |
| 57 | + e.GET("/key", func(c echo.Context) error { |
| 58 | + ctx := c.Request().Context() |
| 59 | + |
| 60 | + authHeader := c.Request().Header.Get("Authorization") |
| 61 | + |
| 62 | + if len(authHeader) == 0 || !strings.HasPrefix(authHeader, BEARER_SCHEMA) { |
| 63 | + return echo.ErrUnauthorized |
| 64 | + } |
| 65 | + |
| 66 | + idToken, err := verifier.Verify(ctx, authHeader[len(BEARER_SCHEMA):]) |
| 67 | + if err != nil { |
| 68 | + return echo.ErrBadRequest |
| 69 | + } |
| 70 | + |
| 71 | + var claims = make(map[string]interface{}) |
| 72 | + if err := idToken.Claims(&claims); err != nil { |
| 73 | + return echo.ErrBadRequest |
| 74 | + } |
| 75 | + |
| 76 | + if ok, _ := evaluator.Evaluate(claims); ok { |
| 77 | + key, err := client.CreateKey(ctx, capabilities, tailscale.WithKeyExpirySeconds(expirySeconds)) |
| 78 | + if err != nil { |
| 79 | + return echo.ErrInternalServerError |
| 80 | + } |
| 81 | + |
| 82 | + return c.JSON(http.StatusOK, &KeyResponse{Key: key.Key}) |
| 83 | + } |
| 84 | + |
| 85 | + return echo.ErrForbidden |
| 86 | + }) |
| 87 | + |
| 88 | + return e.Start(":8080") |
| 89 | +} |
| 90 | + |
| 91 | +func main() { |
| 92 | + if err := start(); err != nil { |
| 93 | + log.Fatal(err) |
| 94 | + } |
| 95 | +} |
0 commit comments