Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use context-aware logging whenever possible #295

Merged
merged 4 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions cmd/tlserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ func (cmd *ServerCommand) Parse(args []string) error {
}

func (cmd *ServerCommand) Run() error {
ctx := context.Background()
// Open database
var db sqlx.Ext
dbx, err := dbutil.OpenDB(cmd.DBURL)
Expand All @@ -154,7 +155,7 @@ func (cmd *ServerCommand) Run() error {
// Create Finder
dbFinder := dbfinder.NewFinder(db)
if cmd.LoadAdmins {
dbFinder.LoadAdmins()
dbFinder.LoadAdmins(ctx)
}

// Create RTFinder, GbfsFinder
Expand Down Expand Up @@ -246,7 +247,7 @@ func (cmd *ServerCommand) Run() error {
// Start server
timeOut := time.Duration(cmd.Timeout) * time.Second
addr := fmt.Sprintf("%s:%s", "0.0.0.0", cmd.Port)
log.Infof("Listening on: %s", addr)
log.For(ctx).Info().Msgf("Listening on: %s", addr)
srv := &http.Server{
Handler: http.TimeoutHandler(root, timeOut, "timeout"),
Addr: addr,
Expand Down
3 changes: 2 additions & 1 deletion docs/openapi/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func GenerateOpenAPI() (*oa.T, error) {
}

func main() {
ctx := context.Background()
args := os.Args
if len(args) != 2 {
exit(errors.New("output file required"))
Expand All @@ -91,7 +92,7 @@ func main() {
exit(err)
}
var validationOpts []oa.ValidationOption
if err := schema.Validate(context.Background(), validationOpts...); err != nil {
if err := schema.Validate(ctx, validationOpts...); err != nil {
exit(err)
}

Expand Down
8 changes: 4 additions & 4 deletions finders/actions/feed_fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,19 +129,18 @@ func RTFetch(ctx context.Context, target string, feedId string, feedUrl string,
return errors.New("invalid rt data")
}
key := fmt.Sprintf("rtdata:%s:%s", target, urlType)
return cfg.RTFinder.AddData(key, rtdata)
return cfg.RTFinder.AddData(ctx, key, rtdata)
}

func GbfsFetch(ctx context.Context, feedId string, feedUrl string) error {
cfg := model.ForContext(ctx)
log := log.For(ctx)
gfeeds, err := cfg.Finder.FindFeeds(ctx, nil, nil, nil, &model.FeedFilter{OnestopID: &feedId})
if err != nil {
log.Error().Err(err).Msg("gbfs-fetch: error loading source feed")
log.For(ctx).Error().Err(err).Msg("gbfs-fetch: error loading source feed")
return err
}
if len(gfeeds) == 0 {
log.Error().Err(err).Msg("gbfs-fetch: source feed not found")
log.For(ctx).Error().Err(err).Msg("gbfs-fetch: source feed not found")
return errors.New("feed not found")
}

Expand All @@ -155,6 +154,7 @@ func GbfsFetch(ctx context.Context, feedId string, feedUrl string) error {
opts.FeedURL = feedUrl
}
feeds, result, err := gbfs.Fetch(
ctx,
tldb.NewPostgresAdapterFromDBX(cfg.Finder.DBX()),
opts,
)
Expand Down
38 changes: 19 additions & 19 deletions finders/azchecker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ type Checker struct {
authz.UnsafeCheckerServer
}

func NewCheckerFromConfig(cfg CheckerConfig, db sqlx.Ext) (*Checker, error) {
func NewCheckerFromConfig(ctx context.Context, cfg CheckerConfig, db sqlx.Ext) (*Checker, error) {
var userClient UserProvider
userClient = NewMockUserProvider()
var fgaClient FGAProvider
Expand All @@ -117,24 +117,24 @@ func NewCheckerFromConfig(cfg CheckerConfig, db sqlx.Ext) (*Checker, error) {
// Create test FGA environment
if cfg.FGALoadModelFile != "" {
if cfg.FGAStoreID == "" {
if _, err := fgac.CreateStore(context.Background(), "test"); err != nil {
if _, err := fgac.CreateStore(ctx, "test"); err != nil {
return nil, err
}
}
if _, err := fgac.CreateModel(context.Background(), cfg.FGALoadModelFile); err != nil {
if _, err := fgac.CreateModel(ctx, cfg.FGALoadModelFile); err != nil {
return nil, err
}
}
// Add test data
for _, tk := range cfg.FGALoadTestData {
ltk, found, err := ekLookup(db, tk)
if !found {
log.Info().Msgf("warning, tuple entities not found in database: %s", tk.String())
log.For(ctx).Info().Msgf("warning, tuple entities not found in database: %s", tk.String())
}
if err != nil {
return nil, err
}
if err := fgaClient.WriteTuple(context.Background(), ltk); err != nil {
if err := fgaClient.WriteTuple(ctx, ltk); err != nil {
return nil, err
}
}
Expand Down Expand Up @@ -340,7 +340,7 @@ func (c *Checker) TenantSave(ctx context.Context, req *authz.TenantSaveRequest)
return nil, ErrUnauthorized
}
newName := t.GetName()
log.Trace().Str("tenantName", newName).Int64("id", tenantId).Msg("TenantSave")
log.For(ctx).Trace().Str("tenantName", newName).Int64("id", tenantId).Msg("TenantSave")
_, err := sq.StatementBuilder.
RunWith(c.db).
PlaceholderFormat(sq.Dollar).
Expand All @@ -360,7 +360,7 @@ func (c *Checker) TenantAddPermission(ctx context.Context, req *authz.TenantModi
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(TenantType, tenantId))
log.Trace().Str("tk", tk.String()).Int64("id", tenantId).Msg("TenantAddPermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", tenantId).Msg("TenantAddPermission")
return &authz.TenantSaveResponse{}, c.fgaClient.SetExclusiveSubjectRelation(ctx, tk, MemberRelation, AdminRelation)
}

Expand All @@ -372,7 +372,7 @@ func (c *Checker) TenantRemovePermission(ctx context.Context, req *authz.TenantM
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(TenantType, tenantId))
log.Trace().Str("tk", tk.String()).Int64("id", tenantId).Msg("TenantRemovePermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", tenantId).Msg("TenantRemovePermission")
return &authz.TenantSaveResponse{}, c.fgaClient.DeleteTuple(ctx, tk)
}

Expand All @@ -388,7 +388,7 @@ func (c *Checker) TenantCreateGroup(ctx context.Context, req *authz.TenantCreate
} else if !check.Actions.CanCreateOrg {
return nil, ErrUnauthorized
}
log.Trace().Str("groupName", groupName).Int64("id", tenantId).Msg("TenantCreateGroup")
log.For(ctx).Trace().Str("groupName", groupName).Int64("id", tenantId).Msg("TenantCreateGroup")
groupId := int64(0)
err := sq.StatementBuilder.
RunWith(c.db).
Expand Down Expand Up @@ -495,7 +495,7 @@ func (c *Checker) GroupSave(ctx context.Context, req *authz.GroupSaveRequest) (*
} else if !check.Actions.CanEdit {
return nil, ErrUnauthorized
}
log.Trace().Str("groupName", newName).Int64("id", groupId).Msg("GroupSave")
log.For(ctx).Trace().Str("groupName", newName).Int64("id", groupId).Msg("GroupSave")
_, err := sq.StatementBuilder.
RunWith(c.db).
PlaceholderFormat(sq.Dollar).
Expand All @@ -515,7 +515,7 @@ func (c *Checker) GroupAddPermission(ctx context.Context, req *authz.GroupModify
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(GroupType, groupId))
log.Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupAddPermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupAddPermission")
return &authz.GroupSaveResponse{}, c.fgaClient.SetExclusiveSubjectRelation(ctx, tk, ViewerRelation, EditorRelation, ManagerRelation)
}

Expand All @@ -527,7 +527,7 @@ func (c *Checker) GroupRemovePermission(ctx context.Context, req *authz.GroupMod
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(GroupType, groupId))
log.Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupRemovePermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupRemovePermission")
return &authz.GroupSaveResponse{}, c.fgaClient.DeleteTuple(ctx, tk)
}

Expand All @@ -540,7 +540,7 @@ func (c *Checker) GroupSetTenant(ctx context.Context, req *authz.GroupSetTenantR
return nil, ErrUnauthorized
}
tk := authz.NewTupleKey().WithSubjectID(TenantType, newTenantId).WithObjectID(GroupType, groupId).WithRelation(ParentRelation)
log.Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupSetTenant")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", groupId).Msg("GroupSetTenant")
return &authz.GroupSetTenantResponse{}, c.fgaClient.SetExclusiveRelation(ctx, tk)
}

Expand Down Expand Up @@ -611,7 +611,7 @@ func (c *Checker) FeedSetGroup(ctx context.Context, req *authz.FeedSetGroupReque
return nil, ErrUnauthorized
}
tk := authz.NewTupleKey().WithSubjectID(GroupType, newGroup).WithObjectID(FeedType, feedId).WithRelation(ParentRelation)
log.Trace().Str("tk", tk.String()).Int64("id", feedId).Msg("FeedSetGroup")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", feedId).Msg("FeedSetGroup")
return &authz.FeedSaveResponse{}, c.fgaClient.SetExclusiveRelation(ctx, tk)
}

Expand Down Expand Up @@ -698,7 +698,7 @@ func (c *Checker) FeedVersionAddPermission(ctx context.Context, req *authz.FeedV
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(FeedVersionType, fvid))
log.Trace().Str("tk", tk.String()).Int64("id", fvid).Msg("FeedVersionAddPermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", fvid).Msg("FeedVersionAddPermission")
return &authz.FeedVersionSaveResponse{}, c.fgaClient.SetExclusiveSubjectRelation(ctx, tk, ViewerRelation, EditorRelation, ManagerRelation)
}

Expand All @@ -710,7 +710,7 @@ func (c *Checker) FeedVersionRemovePermission(ctx context.Context, req *authz.Fe
return nil, ErrUnauthorized
}
tk := req.GetEntityRelation().WithObject(newEntityID(FeedVersionType, fvid))
log.Trace().Str("tk", tk.String()).Int64("id", fvid).Msg("FeedVersionRemovePermission")
log.For(ctx).Trace().Str("tk", tk.String()).Int64("id", fvid).Msg("FeedVersionRemovePermission")
return &authz.FeedVersionSaveResponse{}, c.fgaClient.DeleteTuple(ctx, tk)
}

Expand Down Expand Up @@ -791,12 +791,12 @@ func (c *Checker) checkAction(ctx context.Context, checkAction Action, obj Entit
}
userName := checkUser.ID()
if c.checkGlobalAdmin(checkUser) {
log.Debug().Str("check_user", userName).Str("obj", obj.String()).Str("check_action", checkAction.String()).Msg("global admin action")
log.For(ctx).Debug().Str("check_user", userName).Str("obj", obj.String()).Str("check_action", checkAction.String()).Msg("global admin action")
return true, nil
}
checkTk := authz.NewTupleKey().WithUser(userName).WithObject(obj.Type, obj.Name).WithAction(checkAction)
ret, err := c.fgaClient.Check(ctx, checkTk, ctxtk...)
log.Trace().Str("tk", checkTk.String()).Bool("result", ret).Err(err).Msg("checkAction")
log.For(ctx).Trace().Str("tk", checkTk.String()).Bool("result", ret).Err(err).Msg("checkAction")
return ret, err
}

Expand Down Expand Up @@ -853,7 +853,7 @@ func getEntities[T hasId](ctx context.Context, db sqlx.Ext, ids []int64, table s
var t []T
q := sq.StatementBuilder.Select(cols...).From(table).Where(sq.Eq{"id": ids})
if err := dbutil.Select(ctx, db, q, &t); err != nil {
log.Trace().Err(err)
log.For(ctx).Trace().Err(err)
return nil, err
}
if err := checkIds(t, ids); err != nil {
Expand Down
5 changes: 3 additions & 2 deletions finders/azchecker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1805,21 +1805,22 @@ func checkActionsToMap(v []Action) map[string]bool {
}

func newTestChecker(t testing.TB, url string, testData []testCase) *Checker {
ctx := context.Background()
dbx := testutil.MustOpenTestDB(t)
cfg := CheckerConfig{
FGAEndpoint: url,
FGALoadModelFile: testdata.Path("authz/tls.json"),
GlobalAdmin: "global_admin",
}

checker, err := NewCheckerFromConfig(cfg, dbx)
checker, err := NewCheckerFromConfig(ctx, cfg, dbx)
if err != nil {
t.Fatal(err)
}

// Add test data
for _, tc := range testData {
if err := checker.fgaClient.WriteTuple(context.Background(), dbTupleLookup(t, dbx, tc.TupleKey())); err != nil {
if err := checker.fgaClient.WriteTuple(ctx, dbTupleLookup(t, dbx, tc.TupleKey())); err != nil {
t.Fatal(err)
}
}
Expand Down
Loading
Loading