Standard library · Operating system

os.secret

Passwords and tokens in the Keychain, the Secret Service or the Credential Manager.

import os.secret

A program that remembers a password should not write it to a file. os.secret hands it to the store the operating system already protects, addressed by two names: a service, usually your application id, and a key, usually the account.

  • It can be missing. A server or a minimal Linux desktop may have no Secret Service. Call Available and offer to remember only when it is true.
  • The system may ask. The user can be prompted to unlock the store, or on macOS to let a rebuilt program read an old entry.
  • Text only. A value stops at its first zero byte.

Remembering a password

Store it after a successful sign in, and read it when the program starts.

import os.secret

func remember(user: str, password: str): bool:
    if not secret.Available():
        ret false
    end
    ret secret.Set("com.example.app", user, password)
end

func recall(user: str): str:
    ret secret.Get("com.example.app", user)
end

Forgetting it

When the user turns the option off or signs out, delete the entry.

import os.secret

func forget(user: str):
    _gone := secret.Delete("com.example.app", user)
end

Functions

Available

func Available(): bool
True when the system has a place for secrets that can be used now: the Keychain on macOS, a Secret Service such as GNOME Keyring or KWallet on Linux, the Credential Manager on Windows.

Set

func Set(service: str, key: str, value: str): bool
Stores or replaces a value under a service and a key. False when it could not be stored.

Get

func Get(service: str, key: str): str
Reads the stored value; empty text when there is none.

Delete

func Delete(service: str, key: str): bool
Removes a stored value. False when there was nothing to remove.