Skip to content

Commit 8f6ae94

Browse files
authored
use MetaContext instead of LoginContext in libkb, and branch out (keybase#11573)
- This is the first refactor (of maybe many) to try to standardize our use of contexts passed accross functions - The main goal was to migrate those functions that take a LoginContext as a parameter and migrate them over to MetaContext instead, which can have a LoginContext in addition to other thread-local and global context. - Migrate ActiveDevice, PerUserKey to the new MetaContext system - Make light changes to engine/ but leave some more work TODO, like pushing engine.Context into libkb.MetaContext - Document what's going on in context.md - All code compiles and tests
1 parent 85c4a3b commit 8f6ae94

101 files changed

Lines changed: 1414 additions & 1181 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎go/chat/boxer_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ func getSigningKeyPairForTest(t *testing.T, tc *kbtest.ChatTestContext, u *kbtes
9595
t.Fatal(err)
9696
}
9797
}
98-
kp, err := tc.G.Keyrings.GetSecretKeyWithPassphrase(nil, u.User, u.Passphrase, nil)
98+
kp, err := tc.G.Keyrings.GetSecretKeyWithPassphrase(kbtest.NewMetaContextForTest(*tc), u.User, u.Passphrase, nil)
9999
if err != nil {
100100
t.Fatal(err)
101101
}

‎go/chat/server_test.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ type chatTestUserContext struct {
243243
u *kbtest.FakeUser
244244
h *Server
245245
ri chat1.RemoteInterface
246+
m libkb.MetaContext
246247
}
247248

248249
func (tuc *chatTestUserContext) user() *kbtest.FakeUser {
@@ -356,6 +357,7 @@ func (c *chatTestContext) as(t *testing.T, user *kbtest.FakeUser) *chatTestUserC
356357
u: user,
357358
startCtx: ctx,
358359
ri: ri,
360+
m: libkb.NewMetaContext(ctx, tc.G),
359361
}
360362
c.userContextCache[user.Username] = tuc
361363
return tuc
@@ -4037,7 +4039,8 @@ func TestChatSrvUserReset(t *testing.T) {
40374039
ctc.as(t, users[1]).user(), ctc.as(t, users[2]).user())
40384040

40394041
t.Logf("reset user 1")
4040-
require.NoError(t, ctc.as(t, users[1]).h.G().LoginState().ResetAccount(users[1].Username))
4042+
ctcForUser := ctc.as(t, users[1])
4043+
require.NoError(t, ctcForUser.h.G().LoginState().ResetAccount(ctcForUser.m, users[1].Username))
40414044
select {
40424045
case act := <-listener0.membersUpdate:
40434046
require.Equal(t, act.ConvID, conv.Id)
@@ -4097,7 +4100,8 @@ func TestChatSrvUserReset(t *testing.T) {
40974100
require.Error(t, err)
40984101

40994102
t.Logf("reset user 2")
4100-
require.NoError(t, ctc.as(t, users[2]).h.G().LoginState().ResetAccount(users[2].Username))
4103+
ctcForUser2 := ctc.as(t, users[2])
4104+
require.NoError(t, ctcForUser2.h.G().LoginState().ResetAccount(ctcForUser2.m, users[2].Username))
41014105
select {
41024106
case act := <-listener0.membersUpdate:
41034107
require.Equal(t, act.ConvID, conv.Id)

‎go/client/cmd_test_passphrase.go‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,12 @@ func (s *CmdTestPassphrase) Run() (err error) {
4747
return err
4848
}
4949

50+
ctx := context.Background()
51+
5052
arg := keybase1.PassphrasePromptArg{
51-
GuiArg: libkb.DefaultPassphraseArg(s.G()),
53+
GuiArg: libkb.DefaultPassphraseArg(libkb.NewMetaContext(ctx, s.G())),
5254
}
53-
res, err := cli.PassphrasePrompt(context.TODO(), arg)
55+
res, err := cli.PassphrasePrompt(ctx, arg)
5456
if err != nil {
5557
return err
5658
}

‎go/client/passphrase_prompt.go‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
// promptPassphrase asks the user for a passphrase.
1616
// Used during signup.
1717
func PromptPassphrase(g *libkb.GlobalContext) (keybase1.GetPassphraseRes, error) {
18-
arg := libkb.DefaultPassphraseArg(g)
18+
arg := libkb.DefaultPassphraseArg(libkb.NewMetaContextTODO(g))
1919
arg.WindowTitle = "Passphrase"
2020
arg.Prompt = fmt.Sprintf("Pick a strong passphrase (%d+ characters)", libkb.MinPassphraseLength)
2121
arg.Type = keybase1.PassphraseType_PASS_PHRASE
@@ -25,7 +25,7 @@ func PromptPassphrase(g *libkb.GlobalContext) (keybase1.GetPassphraseRes, error)
2525
// promptNewPassphrase asks the user for a new passphrase.
2626
// Used when changing passphrases.
2727
func PromptNewPassphrase(g *libkb.GlobalContext) (string, error) {
28-
arg := libkb.DefaultPassphraseArg(g)
28+
arg := libkb.DefaultPassphraseArg(libkb.NewMetaContextTODO(g))
2929
arg.WindowTitle = "Pick a new passphrase"
3030
arg.Prompt = fmt.Sprintf("Pick a new strong passphrase (%d+ characters)", libkb.MinPassphraseLength)
3131
arg.Type = keybase1.PassphraseType_VERIFY_PASS_PHRASE
@@ -39,15 +39,16 @@ func PromptNewPassphrase(g *libkb.GlobalContext) (string, error) {
3939
// PromptPaperPhrase asks the user to enter a paper key phrase.
4040
// Used in `rekey paper` command.
4141
func PromptPaperPhrase(g *libkb.GlobalContext) (string, error) {
42-
arg := libkb.DefaultPassphraseArg(g)
42+
m := libkb.NewMetaContextTODO(g)
43+
arg := libkb.DefaultPassphraseArg(m)
4344
arg.WindowTitle = "Enter a paper key"
4445
arg.Prompt = "Enter a paper key"
4546
arg.Type = keybase1.PassphraseType_PAPER_KEY
4647
arg.Features.ShowTyping.Allow = true
4748
arg.Features.ShowTyping.DefaultValue = true
4849

4950
prompter := newClientPrompter(g)
50-
res, err := libkb.GetPassphraseUntilCheck(g, arg, prompter, &libkb.PaperChecker{})
51+
res, err := libkb.GetPassphraseUntilCheck(m, arg, prompter, &libkb.PaperChecker{})
5152
if err != nil {
5253
return "", err
5354
}
@@ -56,20 +57,21 @@ func PromptPaperPhrase(g *libkb.GlobalContext) (string, error) {
5657

5758
func promptPassphraseWithArg(g *libkb.GlobalContext, arg keybase1.GUIEntryArg, promptConfirm string) (keybase1.GetPassphraseRes, error) {
5859
prompter := newClientPrompter(g)
60+
m := libkb.NewMetaContextTODO(g)
5961

6062
firstPrompt := arg.Prompt
6163

6264
for i := 0; i < 10; i++ {
6365
// get the first passphrase
64-
res, err := libkb.GetPassphraseUntilCheckWithChecker(g, arg, prompter, &libkb.CheckPassphraseNew)
66+
res, err := libkb.GetPassphraseUntilCheckWithChecker(m, arg, prompter, &libkb.CheckPassphraseNew)
6567
if err != nil {
6668
return keybase1.GetPassphraseRes{}, err
6769
}
6870

6971
// get confirmation passphrase
7072
arg.RetryLabel = ""
7173
arg.Prompt = promptConfirm
72-
confirm, err := libkb.GetPassphraseUntilCheckWithChecker(g, arg, prompter, &libkb.CheckPassphraseNew)
74+
confirm, err := libkb.GetPassphraseUntilCheckWithChecker(m, arg, prompter, &libkb.CheckPassphraseNew)
7375
if err != nil {
7476
return keybase1.GetPassphraseRes{}, err
7577
}

‎go/doc/context.md‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
2+
# A Note On The Various "Contexts" and "LoginState"
3+
4+
We are in the midst of wide and slow-moving code reorgnization with two major goals:
5+
6+
1. To standardize as much code as possible to take one of three "context" objects, always
7+
as a first argument: (a) Go's standard `context.Context`; (b) our rollup `libkb.MetaContext`;
8+
or (c) our chat-specific context `chat.ChatContext`. We want to eliminate all cases
9+
of functions taking multiple contexts, or contexts not in the first parameter slot, etc.
10+
2. To retire `libkb.LoginState`, `libkb.LoginContext`, and `libkb.Session`, and to migrate
11+
their roles into `libkb.ActiveDevice`.
12+
13+
The goal of `libkb.MetaContext` is to provide both thread-local (see `.Ctx` and `.activeDevice`) and global context (see `.g`). During signup, login or provisioning, we can store a thread local
14+
version of the `ActiveDevice` in the `MetaContext` so that the various login and provisioning
15+
routines can act upon it before exposing it to the rest of the program, since it's still provisional
16+
until login completes. Once the `ActiveDevice` becomes official, then all threads can access it
17+
via `GlobalContext`.
18+
19+
There's a ton of changes we'd have to make in the code to achieve these goals, and
20+
we'd like to proceed in small piecemeal steps so that we can shake out any bugs
21+
as we go.
22+
23+
# History
24+
25+
We have a long and sordid history here, and it might be worth explaining a little bit
26+
of what happened before we describe the strategy for going forward. When we first
27+
started this project, the Go standard `context.Context` hadn't fully formed yet,
28+
so we didn't incorporate it. Instead, we had a notion of `GlobalContext` which applies to
29+
all threads. At first, all threads accessed this global context via a global variable `G`,
30+
but that strategy was terrible for many reasons, and made testing multiple instances of
31+
Keybase in the same address space near-impossible. Thus, we embarked upon a lengthy crusade
32+
to retire to `G` variable and use a combination of dependency-injection and just passing `G`
33+
wherever we could.
34+
35+
Around the same time, we started to adopt the `context.Context` standard, especially
36+
for logging with request-specific tags (useful for debugging). These attempts were sometimes
37+
at odds, so we would up with an inconsistent ordering and placement of these contexts
38+
when passed to functions. Also, though were finally able to retire `G`, we did not succeed
39+
in fully threading `context.Context`s through the code; nor did we finish the project to always
40+
use `context.Context`-aware versions of logging functions.
41+
42+
In addition, we've long had the LoginState/Account/LoginContext/Session family of objects
43+
to manage the user's logged-in state, and to shepherd the user through signup and device
44+
provisioning. We've experienced growing pains and bugs around the current configuration
45+
and long for a simplification. In particular, we're not happy with the Go-channel-based
46+
synchronization primitives at the heart of the state maintenance here, since it's easy
47+
to hit deadlocks hidden behind layers of abstraction. Instead, we want a simple lock-based
48+
model, where those locks are only held briefly, never during a network request (let's say).
49+
50+
# Migration Strategy
51+
52+
## Step 1: Use NIST Tokens for Session Establishment
53+
54+
Status: **completed**
55+
56+
It used to be the case we needed the exclusive lock over Account/LoginContext
57+
to make an API call, since it needed the user's session cookie (and CSRF
58+
token), and it was stored there. This setup made it very easy for API calls to
59+
fight over this locked resource and to stall, especially on application
60+
foregrounding or resumption from a long sleep. So the solution here is to
61+
authenticate a client to the server just based on a signature that the user
62+
can cook up with just her/his public key. Now, API calls are no longer
63+
dependent on Account/LoginContext, and instead depend on `ActiveDevice`, with
64+
the exception of provisioning and signup (i.e., before proper device keys are
65+
established).
66+
67+
## Step 2: Propagate MetaContext from libkb outward
68+
69+
Status: **ongoing**
70+
71+
### Step 2a: Replace LoginContext with a wrapper MetaContext (Part 1)
72+
73+
- Start with `LoginState`-related functions and propagate outwards. Cover `ActiveDevice`,
74+
`PerUserKey`, and bubble up into `engine/` too, but only as necessary.
75+
76+
### Step 2b: Replace LoginContext with a wrapper MetaContext (Part 2)
77+
78+
- Continue with `stellar/` and `ephemeral/` to replace those functions that take
79+
both `context.Context` and `*GlobalContext` to take only `libkb.MetaContext`.
80+
81+
### Step 2c: Move `engine.Context` into `libkb.MetaContext`
82+
83+
- And then change all `engine/` code to take only the `libkb.MetaContext`
84+
85+
## Step 3: Retire LoginState
86+
87+
Once we get to this point, things are a little less clear. The advantage of having
88+
done step 2 first is that a lot of times, we check for a thread-local `LoginContext`
89+
and then fallback to one that we grab from the global state. A lot of code is
90+
duplicated to handle these two cases, since the access pattern is different.
91+
One strategy here might be to move to a `LoginContext`-like object that can be safely
92+
copied, so it's no longer necessary to operate on it from outside of a closure.
93+
94+
### Step 3a: Move LoginSession into ActiveDevice
95+
96+
### Step 3b: Move PassphraseStream into ActiveDevice
97+
98+
### Step 3c: Kill LoginContext
99+
100+
### Step 3d: Kill LoginState
101+
102+
103+
104+
105+
106+
107+

‎go/engine/account_delete.go‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,14 @@ func (e *AccountDelete) SubConsumers() []libkb.UIConsumer {
4646
// Run starts the engine.
4747
func (e *AccountDelete) Run(ctx *Context) error {
4848
username := e.G().GetEnv().GetUsername().String()
49-
arg := libkb.DefaultPassphrasePromptArg(e.G(), username)
49+
mctx := NewMetaContext(e, ctx)
50+
arg := libkb.DefaultPassphrasePromptArg(mctx, username)
5051
res, err := ctx.SecretUI.GetPassphrase(arg, nil)
5152
if err != nil {
5253
return err
5354
}
54-
_, err = e.G().LoginState().VerifyPlaintextPassphrase(res.Passphrase, func(lctx libkb.LoginContext) error {
55-
return libkb.DeleteAccountWithContext(e.G(), lctx, username)
55+
_, err = e.G().LoginState().VerifyPlaintextPassphrase(mctx, res.Passphrase, func(lctx libkb.LoginContext) error {
56+
return libkb.DeleteAccountWithContext(mctx.WithLoginContext(lctx), username)
5657
})
5758

5859
if err != nil {

‎go/engine/bug_3964_repairman_test.go‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ func (a *auditLog) Debug(format string, args ...interface{}) {
3535
*a.lines = append(*a.lines, s)
3636
}
3737
func (a *auditLog) CDebugf(ctx context.Context, format string, args ...interface{}) {
38-
a.l.CDebugf(ctx, format, args...)
38+
s := fmt.Sprintf(format, args...)
39+
a.l.CDebugf(ctx, s)
40+
*a.lines = append(*a.lines, s)
3941
}
4042
func (a *auditLog) Info(format string, args ...interface{}) {
4143
a.l.Info(format, args...)
@@ -101,11 +103,13 @@ func (a *auditLog) SetExternalHandler(handler logger.ExternalHandler) {
101103
func corruptDevice2(dev1 libkb.TestContext, dev2 libkb.TestContext) (*libkb.DeviceKey, error) {
102104
ls1 := dev1.G.LoginState()
103105
ls2 := dev2.G.LoginState()
106+
m := NewMetaContextForTest(dev2)
104107

105108
err := ls1.RunSecretSyncer(dev1.G.Env.GetUID())
106109
if err != nil {
107110
return nil, err
108111
}
112+
109113
var e2 error
110114
var ret libkb.DeviceKey
111115

@@ -136,7 +140,7 @@ func corruptDevice2(dev1 libkb.TestContext, dev2 libkb.TestContext) (*libkb.Devi
136140
if e2 != nil {
137141
return nil, e2
138142
}
139-
if err = goodLksec.LoadServerHalf(nil); err != nil {
143+
if err = goodLksec.LoadServerHalf(m); err != nil {
140144
return nil, err
141145
}
142146

@@ -153,7 +157,7 @@ func corruptDevice2(dev1 libkb.TestContext, dev2 libkb.TestContext) (*libkb.Devi
153157

154158
err = ls2.MutateKeyring(func(krf *libkb.SKBKeyringFile) *libkb.SKBKeyringFile {
155159
for _, b := range krf.Blocks {
156-
raw, _, erroneousMask, err := goodLksec.Decrypt(nil, b.Priv.Data)
160+
raw, _, erroneousMask, err := goodLksec.Decrypt(m, b.Priv.Data)
157161
if err != nil {
158162
e2 = err
159163
return nil
@@ -162,7 +166,7 @@ func corruptDevice2(dev1 libkb.TestContext, dev2 libkb.TestContext) (*libkb.Devi
162166
e2 = errors.New("bad erroneousMask")
163167
return nil
164168
}
165-
b.Priv.Data, e2 = badLskec.Encrypt(raw)
169+
b.Priv.Data, e2 = badLskec.Encrypt(m, raw)
166170
if e2 != nil {
167171
return nil
168172
}
@@ -292,7 +296,7 @@ func checkLKSWorked(t *testing.T, tctx libkb.TestContext, u *FakeUser) {
292296
KeyType: libkb.DeviceEncryptionKeyType,
293297
}
294298
arg := ctx.SecretKeyPromptArg(ska, "tracking signature")
295-
encKey, err := tctx.G.Keyrings.GetSecretKeyWithPrompt(arg)
299+
encKey, err := tctx.G.Keyrings.GetSecretKeyWithPrompt(NewMetaContextForTest(tctx), arg)
296300
if err != nil {
297301
t.Fatal(err)
298302
}
@@ -303,7 +307,7 @@ func checkLKSWorked(t *testing.T, tctx libkb.TestContext, u *FakeUser) {
303307
if err != nil {
304308
t.Fatal(err)
305309
}
306-
pps, err := tctx.G.LoginState().GetPassphraseStream(ctx.SecretUI)
310+
pps, err := tctx.G.LoginState().GetPassphraseStream(NewMetaContextForTest(tctx), ctx.SecretUI)
307311
if err != nil {
308312
t.Fatal(err)
309313
}

0 commit comments

Comments
 (0)