1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2014 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This is the auth-source.el package. It lets users tell Gnus how to
26 ;; authenticate in a single place. Simplicity is the goal. Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (autoload 'rfc2104-hash "rfc2104")
69 (autoload 'plstore-open "plstore")
70 (autoload 'plstore-find "plstore")
71 (autoload 'plstore-put "plstore")
72 (autoload 'plstore-delete "plstore")
73 (autoload 'plstore-save "plstore")
74 (autoload 'plstore-get-file "plstore")
76 (autoload 'epg-make-context "epg")
77 (autoload 'epg-context-set-passphrase-callback "epg")
78 (autoload 'epg-decrypt-string "epg")
79 (autoload 'epg-context-set-armor "epg")
80 (autoload 'epg-encrypt-string "epg")
82 (autoload 'help-mode "help-mode" nil t)
84 (defvar secrets-enabled)
86 (defgroup auth-source nil
87 "Authentication sources."
88 :version "23.1" ;; No Gnus
92 (defcustom auth-source-cache-expiry 7200
93 "How many seconds passwords are cached, or nil to disable
94 expiring. Overrides `password-cache-expiry' through a
98 :type '(choice (const :tag "Never" nil)
99 (const :tag "All Day" 86400)
100 (const :tag "2 Hours" 7200)
101 (const :tag "30 Minutes" 1800)
102 (integer :tag "Seconds")))
104 ;; The slots below correspond with the `auth-source-search' spec,
105 ;; so a backend with :host set, for instance, would match only
106 ;; searches for that host. Normally they are nil.
107 (defclass auth-source-backend ()
108 ((type :initarg :type
112 :documentation "The backend type.")
113 (source :initarg :source
116 :documentation "The backend source.")
121 :documentation "The backend host.")
126 :documentation "The backend user.")
131 :documentation "The backend protocol.")
134 :documentation "Internal backend data.")
135 (create-function :initarg :create-function
139 :documentation "The create function.")
140 (search-function :initarg :search-function
144 :documentation "The search function.")))
146 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
147 (pop3 "pop3" "pop" "pop3s" "110" "995")
151 "List of authentication protocols and their names"
154 :version "23.2" ;; No Gnus
155 :type '(repeat :tag "Authentication Protocols"
156 (cons :tag "Protocol Entry"
157 (symbol :tag "Protocol")
159 (string :tag "Name")))))
161 ;; Generate all the protocols in a format Customize can use.
162 ;; TODO: generate on the fly from auth-source-protocols
163 (defconst auth-source-protocols-customize
165 (let ((p (car-safe a)))
167 :tag (upcase (symbol-name p))
169 auth-source-protocols))
171 (defvar auth-source-creation-defaults nil
172 "Defaults for creating token values. Usually let-bound.")
174 (defvar auth-source-creation-prompts nil
175 "Default prompts for token values. Usually let-bound.")
177 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
179 (defcustom auth-source-save-behavior 'ask
180 "If set, auth-source will respect it for save behavior."
182 :version "23.2" ;; No Gnus
184 :tag "auth-source new token save behavior"
185 (const :tag "Always save" t)
186 (const :tag "Never save" nil)
187 (const :tag "Ask" ask)))
189 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
190 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
192 (defcustom auth-source-netrc-use-gpg-tokens 'never
193 "Set this to tell auth-source when to create GPG password
194 tokens in netrc files. It's either an alist or `never'.
195 Note that if EPA/EPG is not available, this should NOT be used."
197 :version "23.2" ;; No Gnus
199 (const :tag "Always use GPG password tokens" (t gpg))
200 (const :tag "Never use GPG password tokens" never)
201 (repeat :tag "Use a lookup list"
203 (choice :tag "Matcher"
204 (const :tag "Match anything" t)
205 (const :tag "The EPA encrypted file extensions"
206 ,(if (boundp 'epa-file-auto-mode-alist-entry)
208 'epa-file-auto-mode-alist-entry))
210 (regexp :tag "Regular expression"))
211 (choice :tag "What to do"
212 (const :tag "Save GPG-encrypted password tokens" gpg)
213 (const :tag "Don't encrypt tokens" never))))))
215 (defvar auth-source-magic "auth-source-magic ")
217 (defcustom auth-source-do-cache t
218 "Whether auth-source should cache information with `password-cache'."
220 :version "23.2" ;; No Gnus
223 (defcustom auth-source-debug nil
224 "Whether auth-source should log debug messages.
226 If the value is nil, debug messages are not logged.
228 If the value is t, debug messages are logged with `message'. In
229 that case, your authentication data will be in the clear (except
232 If the value is a function, debug messages are logged by calling
233 that function using the same arguments as `message'."
235 :version "23.2" ;; No Gnus
237 :tag "auth-source debugging mode"
238 (const :tag "Log using `message' to the *Messages* buffer" t)
239 (const :tag "Log all trivia with `message' to the *Messages* buffer"
241 (function :tag "Function that takes arguments like `message'")
242 (const :tag "Don't log anything" nil)))
244 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
245 "List of authentication sources.
246 Each entry is the authentication type with optional properties.
247 Entries are tried in the order in which they appear.
248 See Info node `(auth)Help for users' for details.
250 It's best to customize this with `M-x customize-variable' because the choices
251 can get pretty complex."
253 :version "24.1" ;; No Gnus
254 :type `(repeat :tag "Authentication Sources"
256 (string :tag "Just a file")
257 (const :tag "Default Secrets API Collection" default)
258 (const :tag "Login Secrets API Collection" "secrets:Login")
259 (const :tag "Temp Secrets API Collection" "secrets:session")
261 (const :tag "Default internet Mac OS Keychain"
262 macos-keychain-internet)
264 (const :tag "Default generic Mac OS Keychain"
265 macos-keychain-generic)
267 (list :tag "Source definition"
268 (const :format "" :value :source)
269 (choice :tag "Authentication backend choice"
270 (string :tag "Authentication Source (file)")
272 :tag "Secret Service API/KWallet/GNOME Keyring"
273 (const :format "" :value :secrets)
274 (choice :tag "Collection to use"
275 (string :tag "Collection name")
276 (const :tag "Default" default)
277 (const :tag "Login" "Login")
279 :tag "Temporary" "session")))
281 :tag "Mac OS internet Keychain"
283 :value :macos-keychain-internet)
284 (choice :tag "Collection to use"
285 (string :tag "internet Keychain path")
286 (const :tag "default" default)))
288 :tag "Mac OS generic Keychain"
290 :value :macos-keychain-generic)
291 (choice :tag "Collection to use"
292 (string :tag "generic Keychain path")
293 (const :tag "default" default))))
294 (repeat :tag "Extra Parameters" :inline t
295 (choice :tag "Extra parameter"
298 (const :format "" :value :host)
299 (choice :tag "Host (machine) choice"
302 :tag "Regular expression")))
305 (const :format "" :value :port)
309 ,@auth-source-protocols-customize))
310 (list :tag "User" :inline t
311 (const :format "" :value :user)
313 :tag "Personality/Username"
318 (defcustom auth-source-gpg-encrypt-to t
319 "List of recipient keys that `authinfo.gpg' encrypted to.
320 If the value is not a list, symmetric encryption will be used."
322 :version "24.1" ;; No Gnus
323 :type '(choice (const :tag "Symmetric encryption" t)
324 (repeat :tag "Recipient public keys"
325 (string :tag "Recipient public key"))))
327 ;; temp for debugging
328 ;; (unintern 'auth-source-protocols)
329 ;; (unintern 'auth-sources)
330 ;; (customize-variable 'auth-sources)
331 ;; (setq auth-sources nil)
332 ;; (format "%S" auth-sources)
333 ;; (customize-variable 'auth-source-protocols)
334 ;; (setq auth-source-protocols nil)
335 ;; (format "%S" auth-source-protocols)
336 ;; (auth-source-pick nil :host "a" :port 'imap)
337 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
338 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
339 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
340 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
341 ;; (auth-source-protocol-defaults 'imap)
343 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
344 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
345 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
346 (defun auth-source-do-debug (&rest msg)
347 (when auth-source-debug
348 (apply 'auth-source-do-warn msg)))
350 (defun auth-source-do-trivia (&rest msg)
351 (when (or (eq auth-source-debug 'trivia)
352 (functionp auth-source-debug))
353 (apply 'auth-source-do-warn msg)))
355 (defun auth-source-do-warn (&rest msg)
357 ;; set logger to either the function in auth-source-debug or 'message
358 ;; note that it will be 'message if auth-source-debug is nil
359 (if (functionp auth-source-debug)
365 ;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
366 (defun auth-source-read-char-choice (prompt choices)
367 "Read one of CHOICES by `read-char-choice', or `read-char'.
368 `dropdown-list' support is disabled because it doesn't work reliably.
369 Only one of CHOICES will be returned. The PROMPT is augmented
370 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
372 (let* ((prompt-choices
373 (apply 'concat (loop for c in choices
374 collect (format "%c/" c))))
375 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
376 (full-prompt (concat prompt prompt-choices))
379 (while (not (memq k choices))
381 ((fboundp 'read-char-choice)
382 (read-char-choice full-prompt choices))
383 (t (message "%s" full-prompt)
384 (setq k (read-char))))))
387 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
388 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
389 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
390 ;; (:source (:secrets "session") :host t :port t :user "joe")
391 ;; (:source (:secrets "Login") :host t :port t)
392 ;; (:source "~/.authinfo.gpg" :host t :port t)))
394 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
395 ;; (:source (:secrets "session") :host t :port t :user "joe")
396 ;; (:source (:secrets "Login") :host t :port t)
399 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
401 ;; (auth-source-backend-parse "myfile.gpg")
402 ;; (auth-source-backend-parse 'default)
403 ;; (auth-source-backend-parse "secrets:Login")
404 ;; (auth-source-backend-parse 'macos-keychain-internet)
405 ;; (auth-source-backend-parse 'macos-keychain-generic)
406 ;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
407 ;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
409 (defun auth-source-backend-parse (entry)
410 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
411 (auth-source-backend-parse-parameters
414 ;; take 'default and recurse to get it as a Secrets API default collection
415 ;; matching any user, host, and protocol
417 (auth-source-backend-parse '(:source (:secrets default))))
418 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
419 ;; matching any user, host, and protocol
420 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
421 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
423 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
424 ;; Keychain collection matching any user, host, and protocol
425 ((eq entry 'macos-keychain-internet)
426 (auth-source-backend-parse '(:source (:macos-keychain-internet default))))
427 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
428 ;; Keychain collection matching any user, host, and protocol
429 ((eq entry 'macos-keychain-generic)
430 (auth-source-backend-parse '(:source (:macos-keychain-generic default))))
431 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
432 ;; Keychain "XYZ" matching any user, host, and protocol
433 ((and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
435 (auth-source-backend-parse `(:source (:macos-keychain-internet
436 ,(match-string 1 entry)))))
437 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
438 ;; Keychain "XYZ" matching any user, host, and protocol
439 ((and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
441 (auth-source-backend-parse `(:source (:macos-keychain-generic
442 ,(match-string 1 entry)))))
444 ;; take just a file name and recurse to get it as a netrc file
445 ;; matching any user, host, and protocol
447 (auth-source-backend-parse `(:source ,entry)))
449 ;; a file name with parameters
450 ((stringp (plist-get entry :source))
451 (if (equal (file-name-extension (plist-get entry :source)) "plist")
453 (plist-get entry :source)
454 :source (plist-get entry :source)
456 :search-function 'auth-source-plstore-search
457 :create-function 'auth-source-plstore-create
458 :data (plstore-open (plist-get entry :source)))
460 (plist-get entry :source)
461 :source (plist-get entry :source)
463 :search-function 'auth-source-netrc-search
464 :create-function 'auth-source-netrc-create)))
466 ;; the MacOS Keychain
468 (not (null (plist-get entry :source))) ; the source must not be nil
469 (listp (plist-get entry :source)) ; and it must be a list
471 (plist-get (plist-get entry :source) :macos-keychain-generic)
472 (plist-get (plist-get entry :source) :macos-keychain-internet)))
474 (let* ((source-spec (plist-get entry :source))
475 (keychain-generic (plist-get source-spec :macos-keychain-generic))
476 (keychain-type (if keychain-generic
477 'macos-keychain-generic
478 'macos-keychain-internet))
479 (source (plist-get source-spec (if keychain-generic
480 :macos-keychain-generic
481 :macos-keychain-internet))))
483 (when (symbolp source)
484 (setq source (symbol-name source)))
487 (format "Mac OS Keychain (%s)" source)
490 :search-function 'auth-source-macos-keychain-search
491 :create-function 'auth-source-macos-keychain-create)))
493 ;; the Secrets API. We require the package, in order to have a
494 ;; defined value for `secrets-enabled'.
496 (not (null (plist-get entry :source))) ; the source must not be nil
497 (listp (plist-get entry :source)) ; and it must be a list
498 (require 'secrets nil t) ; and we must load the Secrets API
499 secrets-enabled) ; and that API must be enabled
501 ;; the source is either the :secrets key in ENTRY or
502 ;; if that's missing or nil, it's "session"
503 (let ((source (or (plist-get (plist-get entry :source) :secrets)
506 ;; if the source is a symbol, we look for the alias named so,
507 ;; and if that alias is missing, we use "Login"
508 (when (symbolp source)
509 (setq source (or (secrets-get-alias (symbol-name source))
512 (if (featurep 'secrets)
514 (format "Secrets API (%s)" source)
517 :search-function 'auth-source-secrets-search
518 :create-function 'auth-source-secrets-create)
520 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
522 (format "Ignored Secrets API (%s)" source)
529 "auth-source-backend-parse: invalid backend spec: %S" entry)
535 (defun auth-source-backend-parse-parameters (entry backend)
536 "Fills in the extra auth-source-backend parameters of ENTRY.
537 Using the plist ENTRY, get the :host, :port, and :user search
539 (let ((entry (if (stringp entry)
543 (when (setq val (plist-get entry :host))
544 (oset backend host val))
545 (when (setq val (plist-get entry :user))
546 (oset backend user val))
547 (when (setq val (plist-get entry :port))
548 (oset backend port val)))
551 ;; (mapcar 'auth-source-backend-parse auth-sources)
553 (defun* auth-source-search (&rest spec
554 &key type max host user port secret
555 require create delete
557 "Search or modify authentication backends according to SPEC.
559 This function parses `auth-sources' for matches of the SPEC
560 plist. It can optionally create or update an authentication
561 token if requested. A token is just a standard Emacs property
562 list with a :secret property that can be a function; all the
563 other properties will always hold scalar values.
565 Typically the :secret property, if present, contains a password.
567 Common search keys are :max, :host, :port, and :user. In
568 addition, :create specifies how tokens will be or created.
569 Finally, :type can specify which backend types you want to check.
571 A string value is always matched literally. A symbol is matched
572 as its string value, literally. All the SPEC values can be
573 single values (symbol or string) or lists thereof (in which case
574 any of the search terms matches).
576 :create t means to create a token if possible.
578 A new token will be created if no matching tokens were found.
579 The new token will have only the keys the backend requires. For
580 the netrc backend, for instance, that's the user, host, and
585 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
586 (A . \"default A\"))))
587 (auth-source-search :host \"mine\" :type 'netrc :max 1
588 :P \"pppp\" :Q \"qqqq\"
593 \"Search for any entry matching host 'mine' in backends of type
594 'netrc', maximum one result.
596 Create a new entry if you found none. The netrc backend will
597 automatically require host, user, and port. The host will be
598 'mine'. We prompt for the user with default 'defaultUser' and
599 for the port without a default. We will not prompt for A, Q,
600 or P. The resulting token will only have keys user, host, and
603 :create '(A B C) also means to create a token if possible.
605 The behavior is like :create t but if the list contains any
606 parameter, that parameter will be required in the resulting
607 token. The value for that parameter will be obtained from the
608 search parameters or from user input. If any queries are needed,
609 the alist `auth-source-creation-defaults' will be checked for the
610 default value. If the user, host, or port are missing, the alist
611 `auth-source-creation-prompts' will be used to look up the
612 prompts IN THAT ORDER (so the 'user prompt will be queried first,
613 then 'host, then 'port, and finally 'secret). Each prompt string
614 can use %u, %h, and %p to show the user, host, and port.
618 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
619 (A . \"default A\")))
620 (auth-source-creation-prompts
621 '((password . \"Enter IMAP password for %h:%p: \"))))
622 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
623 :P \"pppp\" :Q \"qqqq\"
628 \"Search for any entry matching host 'nonesuch'
629 or 'twosuch' in backends of type 'netrc', maximum one result.
631 Create a new entry if you found none. The netrc backend will
632 automatically require host, user, and port. The host will be
633 'nonesuch' and Q will be 'qqqq'. We prompt for the password
634 with the shown prompt. We will not prompt for Q. The resulting
635 token will have keys user, host, port, A, B, and Q. It will not
636 have P with any value, even though P is used in the search to
637 find only entries that have P set to 'pppp'.\"
639 When multiple values are specified in the search parameter, the
640 user is prompted for which one. So :host (X Y Z) would ask the
641 user to choose between X, Y, and Z.
643 This creation can fail if the search was not specific enough to
644 create a new token (it's up to the backend to decide that). You
645 should `catch' the backend-specific error as usual. Some
646 backends (netrc, at least) will prompt the user rather than throw
649 :require (A B C) means that only results that contain those
650 tokens will be returned. Thus for instance requiring :secret
651 will ensure that any results will actually have a :secret
654 :delete t means to delete any found entries. nil by default.
655 Use `auth-source-delete' in ELisp code instead of calling
656 `auth-source-search' directly with this parameter.
658 :type (X Y Z) will check only those backend types. 'netrc and
659 'secrets are the only ones supported right now.
661 :max N means to try to return at most N items (defaults to 1).
662 When 0 the function will return just t or nil to indicate if any
663 matches were found. More than N items may be returned, depending
664 on the search and the backend.
666 :host (X Y Z) means to match only hosts X, Y, or Z according to
667 the match rules above. Defaults to t.
669 :user (X Y Z) means to match only users X, Y, or Z according to
670 the match rules above. Defaults to t.
672 :port (P Q R) means to match only protocols P, Q, or R.
675 :K (V1 V2 V3) for any other key K will match values V1, V2, or
676 V3 (note the match rules above).
678 The return value is a list with at most :max tokens. Each token
679 is a plist with keys :backend :host :port :user, plus any other
680 keys provided by the backend (notably :secret). But note the
681 exception for :max 0, which see above.
683 The token can hold a :save-function key. If you call that, the
684 user will be prompted to save the data to the backend. You can't
685 request that this should happen right after creation, because
686 `auth-source-search' has no way of knowing if the token is
687 actually useful. So the caller must arrange to call this function.
689 The token's :secret key can hold a function. In that case you
690 must call it to obtain the actual value."
691 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
693 (ignored-keys '(:require :create :delete :max))
694 (keys (loop for i below (length spec) by 2
695 unless (memq (nth i spec) ignored-keys)
696 collect (nth i spec)))
697 (cached (auth-source-remembered-p spec))
698 ;; note that we may have cached results but found is still nil
699 ;; (there were no results from the search)
700 (found (auth-source-recall spec))
701 filtered-backends accessor-key backend)
703 (if (and cached auth-source-do-cache)
704 (auth-source-do-debug
705 "auth-source-search: found %d CACHED results matching %S"
709 (or (eq t create) (listp create)) t
710 "Invalid auth-source :create parameter (must be t or a list): %s %s")
714 "Invalid auth-source :require parameter (must be a list): %s")
716 (setq filtered-backends (copy-sequence backends))
717 (dolist (backend backends)
719 ;; ignore invalid slots
720 (condition-case signal
721 (unless (eval `(auth-source-search-collection
723 (oref backend ,key)))
724 (setq filtered-backends (delq backend filtered-backends))
726 (invalid-slot-name))))
728 (auth-source-do-trivia
729 "auth-source-search: found %d backends matching %S"
730 (length filtered-backends) spec)
732 ;; (debug spec "filtered" filtered-backends)
733 ;; First go through all the backends without :create, so we can
735 (setq found (auth-source-search-backends filtered-backends
739 ;; create is always nil here
743 (auth-source-do-debug
744 "auth-source-search: found %d results (max %d) matching %S"
745 (length found) max spec)
747 ;; If we didn't find anything, then we allow the backend(s) to
748 ;; create the entries.
751 (setq found (auth-source-search-backends filtered-backends
757 (auth-source-do-debug
758 "auth-source-search: CREATED %d results (max %d) matching %S"
759 (length found) max spec))
761 ;; note we remember the lack of result too, if it's applicable
762 (when auth-source-do-cache
763 (auth-source-remember spec found)))
767 (defun auth-source-search-backends (backends spec max create delete require)
769 (dolist (backend backends)
770 (when (> max (length matches)) ; when we need more matches...
771 (let* ((bmatches (apply
772 (slot-value backend 'search-function)
774 :type (slot-value backend :type)
775 ;; note we're overriding whatever the spec
776 ;; has for :require, :create, and :delete
782 (auth-source-do-trivia
783 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
784 (length bmatches) max
785 (slot-value backend :type)
786 (slot-value backend :source)
788 (setq matches (append matches bmatches))))))
791 ;; (auth-source-search :max 1)
792 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
793 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
794 ;; (auth-source-search :host "nonesuch" :type 'secrets)
796 (defun* auth-source-delete (&rest spec
799 "Delete entries from the authentication backends according to SPEC.
800 Calls `auth-source-search' with the :delete property in SPEC set to t.
801 The backend may not actually delete the entries.
803 Returns the deleted entries."
804 (auth-source-search (plist-put spec :delete t)))
806 (defun auth-source-search-collection (collection value)
807 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
808 (when (and (atom collection) (not (eq t collection)))
809 (setq collection (list collection)))
811 ;; (debug :collection collection :value value)
812 (or (eq collection t)
814 (equal collection value)
815 (member value collection)))
817 (defvar auth-source-netrc-cache nil)
819 (defun auth-source-forget-all-cached ()
820 "Forget all cached auth-source data."
822 (loop for sym being the symbols of password-data
823 ;; when the symbol name starts with auth-source-magic
824 when (string-match (concat "^" auth-source-magic)
827 do (password-cache-remove (symbol-name sym)))
828 (setq auth-source-netrc-cache nil))
830 (defun auth-source-format-cache-entry (spec)
831 "Format SPEC entry to put it in the password cache."
832 (concat auth-source-magic (format "%S" spec)))
834 (defun auth-source-remember (spec found)
835 "Remember FOUND search results for SPEC."
836 (let ((password-cache-expiry auth-source-cache-expiry))
838 (auth-source-format-cache-entry spec) found)))
840 (defun auth-source-recall (spec)
841 "Recall FOUND search results for SPEC."
842 (password-read-from-cache (auth-source-format-cache-entry spec)))
844 (defun auth-source-remembered-p (spec)
845 "Check if SPEC is remembered."
847 (auth-source-format-cache-entry spec)))
849 (defun auth-source-forget (spec)
850 "Forget any cached data matching SPEC exactly.
852 This is the same SPEC you passed to `auth-source-search'.
853 Returns t or nil for forgotten or not found."
854 (password-cache-remove (auth-source-format-cache-entry spec)))
856 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
858 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
859 ;; (auth-source-remembered-p '(:host "wedd"))
860 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
861 ;; (auth-source-remembered-p '(:host "xedd"))
862 ;; (auth-source-remembered-p '(:host "zedd"))
863 ;; (auth-source-recall '(:host "xedd"))
864 ;; (auth-source-recall '(:host t))
865 ;; (auth-source-forget+ :host t)
867 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
868 "Forget any cached data matching SPEC. Returns forgotten count.
870 This is not a full `auth-source-search' spec but works similarly.
871 For instance, \(:host \"myhost\" \"yourhost\") would find all the
872 cached data that was found with a search for those two hosts,
873 while \(:host t) would find all host entries."
876 (loop for sym being the symbols of password-data
877 ;; when the symbol name matches with auth-source-magic
878 when (and (setq sname (symbol-name sym))
879 (string-match (concat "^" auth-source-magic "\\(.+\\)")
881 ;; and the spec matches what was stored in the cache
882 (auth-source-specmatchp spec (read (match-string 1 sname))))
885 (password-cache-remove sname)
889 (defun auth-source-specmatchp (spec stored)
890 (let ((keys (loop for i below (length spec) by 2
891 collect (nth i spec))))
894 (unless (auth-source-search-collection (plist-get stored key)
895 (plist-get spec key))
899 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
900 ;; (auth-source-pick-first-password :port "imap")
901 (defun auth-source-pick-first-password (&rest spec)
902 "Pick the first secret found from applying SPEC to `auth-source-search'."
903 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
904 (secret (plist-get result :secret)))
906 (if (functionp secret)
910 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
911 (defun auth-source-format-prompt (prompt alist)
912 "Format PROMPT using %x (for any character x) specifiers in ALIST."
914 (let ((c (nth 0 cell))
917 (setq prompt (replace-regexp-in-string (format "%%%c" c)
922 (defun auth-source-ensure-strings (values)
923 (unless (listp values)
924 (setq values (list values)))
925 (mapcar (lambda (value)
931 ;;; Backend specific parsing: netrc/authinfo backend
933 (defun auth-source--aput-1 (alist key val)
936 (while (and (consp rest) (not (equal key (caar rest))))
937 (push (pop rest) seen))
939 (if (null rest) alist
940 (nconc (nreverse seen)
941 (if (equal key (caar rest)) (cdr rest) rest))))))
942 (defmacro auth-source--aput (var key val)
943 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
945 (defun auth-source--aget (alist key)
946 (cdr (assoc key alist)))
948 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
949 (defun* auth-source-netrc-parse (&rest
951 &key file max host user port delete require
953 "Parse FILE and return a list of all entries in the file.
954 Note that the MAX parameter is used so we can exit the parse early."
956 ;; We got already parsed contents; just return it.
958 (when (file-exists-p file)
959 (setq port (auth-source-ensure-strings port))
961 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
963 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
964 (cached-mtime (plist-get cached :mtime))
965 (cached-secrets (plist-get cached :secret))
966 (check (lambda(alist)
968 (auth-source-search-collection
971 (auth-source--aget alist "machine")
972 (auth-source--aget alist "host")
974 (auth-source-search-collection
977 (auth-source--aget alist "login")
978 (auth-source--aget alist "account")
979 (auth-source--aget alist "user")
981 (auth-source-search-collection
984 (auth-source--aget alist "port")
985 (auth-source--aget alist "protocol")
988 ;; the required list of keys is nil, or
990 ;; every element of require is in n(ormalized)
991 (let ((n (nth 0 (auth-source-netrc-normalize
992 (list alist) file))))
993 (loop for req in require
994 always (plist-get n req)))))))
997 (if (and (functionp cached-secrets)
999 (nth 5 (file-attributes file))))
1001 (auth-source-do-trivia
1002 "auth-source-netrc-parse: using CACHED file data for %s"
1004 (insert (funcall cached-secrets)))
1005 (insert-file-contents file)
1006 ;; cache all netrc files (used to be just .gpg files)
1007 ;; Store the contents of the file heavily encrypted in memory.
1008 ;; (note for the irony-impaired: they are just obfuscated)
1010 auth-source-netrc-cache file
1011 (list :mtime (nth 5 (file-attributes file))
1012 :secret (lexical-let ((v (mapcar '1+ (buffer-string))))
1013 (lambda () (apply 'string (mapcar '1- v)))))))
1014 (goto-char (point-min))
1015 (let ((entries (auth-source-netrc-parse-entries check max))
1017 (while (setq alist (pop entries))
1018 (push (nreverse alist) result)))
1020 (when (< 0 modified)
1021 (when auth-source-gpg-encrypt-to
1022 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1023 ;; this buffer lets epa-file skip the key selection query
1024 ;; (see the `local-variable-p' check in
1025 ;; `epa-file-write-region').
1026 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1027 (make-local-variable 'epa-file-encrypt-to))
1028 (if (listp auth-source-gpg-encrypt-to)
1029 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1031 ;; ask AFTER we've successfully opened the file
1032 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1034 (write-region (point-min) (point-max) file nil 'silent)
1035 (auth-source-do-debug
1036 "auth-source-netrc-parse: modified %d lines in %s"
1039 (nreverse result))))))
1041 (defun auth-source-netrc-parse-next-interesting ()
1042 "Advance to the next interesting position in the current buffer."
1043 ;; If we're looking at a comment or are at the end of the line, move forward
1044 (while (or (looking-at "#")
1048 (skip-chars-forward "\t "))
1050 (defun auth-source-netrc-parse-one ()
1051 "Read one thing from the current buffer."
1052 (auth-source-netrc-parse-next-interesting)
1054 (when (or (looking-at "'\\([^']*\\)'")
1055 (looking-at "\"\\([^\"]*\\)\"")
1056 (looking-at "\\([^ \t\n]+\\)"))
1057 (forward-char (length (match-string 0)))
1058 (auth-source-netrc-parse-next-interesting)
1059 (match-string-no-properties 1)))
1061 ;; with thanks to org-mode
1062 (defsubst auth-source-current-line (&optional pos)
1064 (and pos (goto-char pos))
1065 ;; works also in narrowed buffer, because we start at 1, not point-min
1066 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1068 (defun auth-source-netrc-parse-entries(check max)
1069 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1070 (let ((adder (lambda(check alist all)
1073 (> max (length all))
1074 (funcall check alist))
1077 item item2 all alist default)
1078 (while (setq item (auth-source-netrc-parse-one))
1079 (setq default (equal item "default"))
1080 ;; We're starting a new machine. Save the old one.
1083 (equal item "machine")))
1084 ;; (auth-source-do-trivia
1085 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1086 (setq all (funcall adder check alist all)
1088 ;; In default entries, we don't have a next token.
1089 ;; We store them as ("machine" . t)
1091 (push (cons "machine" t) alist)
1092 ;; Not a default entry. Grab the next item.
1093 (when (setq item2 (auth-source-netrc-parse-one))
1094 ;; Did we get a "machine" value?
1095 (if (equal item2 "machine")
1098 "%s: Unexpected 'machine' token at line %d"
1099 "auth-source-netrc-parse-entries"
1100 (auth-source-current-line))
1102 (push (cons item item2) alist)))))
1104 ;; Clean up: if there's an entry left over, use it.
1106 (setq all (funcall adder check alist all))
1107 ;; (auth-source-do-trivia
1108 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1112 (defvar auth-source-passphrase-alist nil)
1114 (defun auth-source-token-passphrase-callback-function (context key-id file)
1115 (let* ((file (file-truename file))
1116 (entry (assoc file auth-source-passphrase-alist))
1118 ;; return the saved passphrase, calling a function if needed
1119 (or (copy-sequence (if (functionp (cdr entry))
1120 (funcall (cdr entry))
1124 (setq entry (list file))
1125 (push entry auth-source-passphrase-alist))
1128 (format "Passphrase for %s tokens: " file)
1130 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1134 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1135 (defun auth-source-epa-extract-gpg-token (secret file)
1136 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1137 FILE is the file from which we obtained this token."
1138 (when (string-match "^gpg:\\(.+\\)" secret)
1139 (setq secret (base64-decode-string (match-string 1 secret))))
1140 (let ((context (epg-make-context 'OpenPGP))
1142 (epg-context-set-passphrase-callback
1144 (cons #'auth-source-token-passphrase-callback-function
1146 (epg-decrypt-string context secret)))
1148 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1149 (defun auth-source-epa-make-gpg-token (secret file)
1150 (let ((context (epg-make-context 'OpenPGP))
1151 (pp-escape-newlines nil)
1153 (epg-context-set-armor context t)
1154 (epg-context-set-passphrase-callback
1156 (cons #'auth-source-token-passphrase-callback-function
1158 (setq cipher (epg-encrypt-string context secret nil))
1161 (base64-encode-region (point-min) (point-max) t)
1162 (concat "gpg:" (buffer-substring-no-properties
1166 (defun auth-source-netrc-normalize (alist filename)
1167 (mapcar (lambda (entry)
1169 (while (setq item (pop entry))
1170 (let ((k (car item))
1173 ;; apply key aliases
1174 (setq k (cond ((member k '("machine")) "host")
1175 ((member k '("login" "account")) "user")
1176 ((member k '("protocol")) "port")
1177 ((member k '("password")) "secret")
1180 ;; send back the secret in a function (lexical binding)
1181 (when (equal k "secret")
1182 (setq v (lexical-let ((lexv v)
1183 (token-decoder nil))
1184 (when (string-match "^gpg:" lexv)
1185 ;; it's a GPG token: create a token decoder
1186 ;; which unsets itself once
1190 (auth-source-epa-extract-gpg-token
1193 (setq token-decoder nil)))))
1196 (setq lexv (funcall token-decoder lexv)))
1198 (setq ret (plist-put ret
1199 (intern (concat ":" k))
1204 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1207 (defun* auth-source-netrc-search (&rest
1209 &key backend require create delete
1210 type max host user port
1212 "Given a property list SPEC, return search matches from the :backend.
1213 See `auth-source-search' for details on SPEC."
1214 ;; just in case, check that the type is correct (null or same as the backend)
1215 (assert (or (null type) (eq type (oref backend type)))
1216 t "Invalid netrc search: %s %s")
1218 (let ((results (auth-source-netrc-normalize
1219 (auth-source-netrc-parse
1223 :file (oref backend source)
1227 (oref backend source))))
1229 ;; if we need to create an entry AND none were found to match
1233 ;; create based on the spec and record the value
1235 ;; if the user did not want to create the entry
1236 ;; in the file, it will be returned
1237 (apply (slot-value backend 'create-function) spec)
1238 ;; if not, we do the search again without :create
1239 ;; to get the updated data.
1241 ;; the result will be returned, even if the search fails
1242 (apply 'auth-source-netrc-search
1243 (plist-put spec :create nil)))))
1246 (defun auth-source-netrc-element-or-first (v)
1251 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1252 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1254 (defun* auth-source-netrc-create (&rest spec
1256 secret host user port create
1258 (let* ((base-required '(host user port secret))
1259 ;; we know (because of an assertion in auth-source-search) that the
1260 ;; :create parameter is either t or a list (which includes nil)
1261 (create-extra (if (eq t create) nil create))
1262 (current-data (car (auth-source-search :max 1
1265 (required (append base-required create-extra))
1266 (file (oref backend source))
1268 ;; `valist' is an alist
1270 ;; `artificial' will be returned if no creation is needed
1273 ;; only for base required elements (defined as function parameters):
1274 ;; fill in the valist with whatever data we may have from the search
1275 ;; we complete the first value if it's a list and use the value otherwise
1276 (dolist (br base-required)
1277 (when (symbol-value br)
1278 (let ((br-choice (cond
1279 ;; all-accepting choice (predicate is t)
1280 ((eq t (symbol-value br)) nil)
1281 ;; just the value otherwise
1282 (t (symbol-value br)))))
1284 (auth-source--aput valist br br-choice)))))
1286 ;; for extra required elements, see if the spec includes a value for them
1287 (dolist (er create-extra)
1288 (let ((name (concat ":" (symbol-name er)))
1289 (keys (loop for i below (length spec) by 2
1290 collect (nth i spec))))
1292 (when (equal (symbol-name k) name)
1293 (auth-source--aput valist er (plist-get spec k))))))
1295 ;; for each required element
1296 (dolist (r required)
1297 (let* ((data (auth-source--aget valist r))
1298 ;; take the first element if the data is a list
1299 (data (or (auth-source-netrc-element-or-first data)
1300 (plist-get current-data
1301 (intern (format ":%s" r) obarray))))
1302 ;; this is the default to be offered
1303 (given-default (auth-source--aget
1304 auth-source-creation-defaults r))
1305 ;; the default supplementals are simple:
1306 ;; for the user, try `given-default' and then (user-login-name);
1307 ;; otherwise take `given-default'
1309 ((and (not given-default) (eq r 'user))
1312 (printable-defaults (list
1315 (auth-source-netrc-element-or-first
1316 (auth-source--aget valist 'user))
1317 (plist-get artificial :user)
1321 (auth-source-netrc-element-or-first
1322 (auth-source--aget valist 'host))
1323 (plist-get artificial :host)
1327 (auth-source-netrc-element-or-first
1328 (auth-source--aget valist 'port))
1329 (plist-get artificial :port)
1331 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1333 (secret "%p password for %u@%h: ")
1334 (user "%p user name for %h: ")
1335 (host "%p host name for user %u: ")
1336 (port "%p port for %u@%h: "))
1337 (format "Enter %s (%%u@%%h:%%p): " r)))
1338 (prompt (auth-source-format-prompt
1340 `((?u ,(auth-source--aget printable-defaults 'user))
1341 (?h ,(auth-source--aget printable-defaults 'host))
1342 (?p ,(auth-source--aget printable-defaults 'port))))))
1344 ;; Store the data, prompting for the password if needed.
1347 ;; Special case prompt for passwords.
1348 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1349 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1350 (let* ((ep (format "Use GPG password tokens in %s?" file))
1353 ((eq auth-source-netrc-use-gpg-tokens 'never)
1355 ((listp auth-source-netrc-use-gpg-tokens)
1356 (let ((check (copy-sequence
1357 auth-source-netrc-use-gpg-tokens))
1360 (setq item (pop check))
1361 (when (or (eq (car item) t)
1362 (string-match (car item) file))
1363 (setq ret (cdr item))
1364 (setq check nil)))))
1366 (plain (or (eval default) (read-passwd prompt))))
1367 ;; ask if we don't know what to do (in which case
1368 ;; auth-source-netrc-use-gpg-tokens must be a list)
1370 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1371 ;; TODO: save the defcustom now? or ask?
1372 (setq auth-source-netrc-use-gpg-tokens
1373 (cons `(,file ,gpg-encrypt)
1374 auth-source-netrc-use-gpg-tokens)))
1375 (if (eq gpg-encrypt 'gpg)
1376 (auth-source-epa-make-gpg-token plain file)
1378 (if (stringp default)
1379 (read-string (if (string-match ": *\\'" prompt)
1380 (concat (substring prompt 0 (match-beginning 0))
1381 " (default " default "): ")
1382 (concat prompt "(default " default ") "))
1387 (setq artificial (plist-put artificial
1388 (intern (concat ":" (symbol-name r)))
1390 (lexical-let ((data data))
1394 ;; When r is not an empty string...
1395 (when (and (stringp data)
1396 (< 0 (length data)))
1397 ;; this function is not strictly necessary but I think it
1398 ;; makes the code clearer -tzz
1399 (let ((printer (lambda ()
1400 ;; append the key (the symbol name of r)
1401 ;; and the value in r
1404 (if (zerop (length add)) "" " ")
1405 ;; remap auth-source tokens to netrc
1410 (port "port") ; redundant but clearer
1411 (t (symbol-name r)))
1412 (if (string-match "[\"# ]" data)
1415 (setq add (concat add (funcall printer)))))))
1420 (lexical-let ((file file)
1422 (lambda () (auth-source-netrc-saver file add))))
1426 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1427 (defun auth-source-netrc-saver (file add)
1428 "Save a line ADD in FILE, prompting along the way.
1429 Respects `auth-source-save-behavior'. Uses
1430 `auth-source-netrc-cache' to avoid prompting more than once."
1431 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1432 (cached (assoc key auth-source-netrc-cache)))
1435 (auth-source-do-trivia
1436 "auth-source-netrc-saver: found previous run for key %s, returning"
1439 (when (file-exists-p file)
1440 (insert-file-contents file))
1441 (when auth-source-gpg-encrypt-to
1442 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1443 ;; this buffer lets epa-file skip the key selection query
1444 ;; (see the `local-variable-p' check in
1445 ;; `epa-file-write-region').
1446 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1447 (make-local-variable 'epa-file-encrypt-to))
1448 (if (listp auth-source-gpg-encrypt-to)
1449 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1450 ;; we want the new data to be found first, so insert at beginning
1451 (goto-char (point-min))
1453 ;; Ask AFTER we've successfully opened the file.
1454 (let ((prompt (format "Save auth info to file %s? " file))
1455 (done (not (eq auth-source-save-behavior 'ask)))
1456 (bufname "*auth-source Help*")
1459 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1463 (with-output-to-temp-buffer bufname
1465 (concat "(y)es, save\n"
1466 "(n)o but use the info\n"
1467 "(N)o and don't ask to save again\n"
1469 "(?) for help as you can see.\n"))
1470 ;; Why? Doesn't with-output-to-temp-buffer already do
1471 ;; the exact same thing anyway? --Stef
1472 (set-buffer standard-output)
1479 (customize-save-variable 'auth-source-save-behavior nil))
1480 (?e (setq add (read-string "Line to add: " add)))
1483 (when (get-buffer-window bufname)
1484 (delete-window (get-buffer-window bufname)))
1486 ;; Make sure the info is not saved.
1487 (when (null auth-source-save-behavior)
1490 (when (< 0 (length add))
1495 (write-region (point-min) (point-max) file nil 'silent)
1496 ;; Make the .authinfo file non-world-readable.
1497 (set-file-modes file #o600)
1498 (auth-source-do-debug
1499 "auth-source-netrc-create: wrote 1 new line to %s"
1501 (message "Saved new authentication information to %s" file)
1503 (auth-source--aput auth-source-netrc-cache key "ran"))))
1505 ;;; Backend specific parsing: Secrets API backend
1507 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1508 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1509 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1510 ;; (let ((auth-sources '(default))) (auth-source-search))
1511 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1512 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1514 (defun* auth-source-secrets-search (&rest
1516 &key backend create delete label
1517 type max host user port
1519 "Search the Secrets API; spec is like `auth-source'.
1521 The :label key specifies the item's label. It is the only key
1522 that can specify a substring. Any :label value besides a string
1523 will allow any label.
1525 All other search keys must match exactly. If you need substring
1526 matching, do a wider search and narrow it down yourself.
1528 You'll get back all the properties of the token as a plist.
1530 Here's an example that looks for the first item in the 'Login'
1533 \(let ((auth-sources '(\"secrets:Login\")))
1534 (auth-source-search :max 1)
1536 Here's another that looks for the first item in the 'Login'
1537 Secrets collection whose label contains 'gnus':
1539 \(let ((auth-sources '(\"secrets:Login\")))
1540 (auth-source-search :max 1 :label \"gnus\")
1542 And this one looks for the first item in the 'Login' Secrets
1543 collection that's a Google Chrome entry for the git.gnus.org site
1544 authentication tokens:
1546 \(let ((auth-sources '(\"secrets:Login\")))
1547 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1551 (assert (not create) nil
1552 "The Secrets API auth-source backend doesn't support creation yet")
1554 ;; (secrets-delete-item coll elt)
1555 (assert (not delete) nil
1556 "The Secrets API auth-source backend doesn't support deletion yet")
1558 (let* ((coll (oref backend source))
1559 (max (or max 5000)) ; sanity check: default to stop at 5K
1560 (ignored-keys '(:create :delete :max :backend :label :require :type))
1561 (search-keys (loop for i below (length spec) by 2
1562 unless (memq (nth i spec) ignored-keys)
1563 collect (nth i spec)))
1564 ;; build a search spec without the ignored keys
1565 ;; if a search key is nil or t (match anything), we skip it
1566 (search-spec (apply 'append (mapcar
1568 (if (or (null (plist-get spec k))
1569 (eq t (plist-get spec k)))
1571 (list k (plist-get spec k))))
1573 ;; needed keys (always including host, login, port, and secret)
1574 (returned-keys (mm-delete-duplicates (append
1575 '(:host :login :port :secret)
1577 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1578 unless (and (stringp label)
1579 (not (string-match label item)))
1581 ;; TODO: respect max in `secrets-search-items', not after the fact
1582 (items (butlast items (- (length items) max)))
1583 ;; convert the item name to a full plist
1584 (items (mapcar (lambda (item)
1586 ;; make an entry for the secret (password) element
1589 (lexical-let ((v (secrets-get-secret coll item)))
1591 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1593 (mapcar (lambda (entry)
1594 (list (car entry) (cdr entry)))
1595 (secrets-get-attributes coll item)))))
1597 ;; ensure each item has each key in `returned-keys'
1598 (items (mapcar (lambda (plist)
1601 (mapcar (lambda (req)
1602 (if (plist-get plist req)
1610 (defun* auth-source-secrets-create (&rest
1612 &key backend type max host user port
1615 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1618 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1620 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1621 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1622 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1623 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1625 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1626 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1627 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1628 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1630 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1631 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1633 (defun* auth-source-macos-keychain-search (&rest
1635 &key backend create delete label
1636 type max host user port
1638 "Search the MacOS Keychain; spec is like `auth-source'.
1640 All search keys must match exactly. If you need substring
1641 matching, do a wider search and narrow it down yourself.
1643 You'll get back all the properties of the token as a plist.
1645 The :type key is either 'macos-keychain-internet or
1646 'macos-keychain-generic.
1648 For the internet keychain type, the :label key searches the
1649 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1650 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1651 and :port maps to \"-P PORT\" or \"-r PROT\"
1652 (note PROT has to be a 4-character string).
1654 For the generic keychain type, the :label key searches the item's
1655 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1656 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1657 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1659 Here's an example that looks for the first item in the default
1660 generic MacOS Keychain:
1662 \(let ((auth-sources '(macos-keychain-generic)))
1663 (auth-source-search :max 1)
1665 Here's another that looks for the first item in the internet
1666 MacOS Keychain collection whose label is 'gnus':
1668 \(let ((auth-sources '(macos-keychain-internet)))
1669 (auth-source-search :max 1 :label \"gnus\")
1671 And this one looks for the first item in the internet keychain
1672 entries for git.gnus.org:
1674 \(let ((auth-sources '(macos-keychain-internet\")))
1675 (auth-source-search :max 1 :host \"git.gnus.org\"))
1678 (assert (not create) nil
1679 "The MacOS Keychain auth-source backend doesn't support creation yet")
1681 ;; (macos-keychain-delete-item coll elt)
1682 (assert (not delete) nil
1683 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1685 (let* ((coll (oref backend source))
1686 (max (or max 5000)) ; sanity check: default to stop at 5K
1687 (ignored-keys '(:create :delete :max :backend :label))
1688 (search-keys (loop for i below (length spec) by 2
1689 unless (memq (nth i spec) ignored-keys)
1690 collect (nth i spec)))
1691 ;; build a search spec without the ignored keys
1692 ;; if a search key is nil or t (match anything), we skip it
1693 (search-spec (apply 'append (mapcar
1695 (if (or (null (plist-get spec k))
1696 (eq t (plist-get spec k)))
1698 (list k (plist-get spec k))))
1700 ;; needed keys (always including host, login, port, and secret)
1701 (returned-keys (mm-delete-duplicates (append
1702 '(:host :login :port :secret)
1704 (items (apply 'auth-source-macos-keychain-search-items
1710 ;; ensure each item has each key in `returned-keys'
1711 (items (mapcar (lambda (plist)
1714 (mapcar (lambda (req)
1715 (if (plist-get plist req)
1723 (defun* auth-source-macos-keychain-search-items (coll type max
1729 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1730 (args `(,(if keychain-generic
1731 "find-generic-password"
1732 "find-internet-password")
1734 (ret (list :type type)))
1736 (setq args (append args (list "-l" label))))
1738 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1740 (setq args (append args (list "-a" user))))
1743 (if keychain-generic
1744 (setq args (append args (list "-s" port)))
1745 (setq args (append args (list
1746 (if (string-match "[0-9]+" port) "-P" "-r")
1749 (unless (equal coll "default")
1750 (setq args (append args (list coll))))
1753 (apply 'call-process "/usr/bin/security" nil t nil args)
1754 (goto-char (point-min))
1757 ((looking-at "^password: \"\\(.+\\)\"$")
1758 (auth-source-macos-keychain-result-append
1762 (lexical-let ((v (match-string 1)))
1764 ;; TODO: check if this is really the label
1765 ;; match 0x00000007 <blob>="AppleID"
1766 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1767 (auth-source-macos-keychain-result-append
1772 ;; match "crtr"<uint32>="aapl"
1773 ;; match "svce"<blob>="AppleID"
1774 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1775 (auth-source-macos-keychain-result-append
1781 ;; return `ret' iff it has the :secret key
1782 (and (plist-get ret :secret) (list ret))))
1784 (defun auth-source-macos-keychain-result-append (result generic k v)
1787 ((equal k "acct") "user")
1788 ;; for generic keychains, creator is host, service is port
1789 ((and generic (equal k "crtr")) "host")
1790 ((and generic (equal k "svce")) "port")
1791 ;; for internet keychains, protocol is port, server is host
1792 ((and (not generic) (equal k "ptcl")) "port")
1793 ((and (not generic) (equal k "srvr")) "host")
1796 (push (intern (format ":%s" k)) result))
1798 (defun* auth-source-macos-keychain-create (&rest
1800 &key backend type max host user port
1805 ;;; Backend specific parsing: PLSTORE backend
1807 (defun* auth-source-plstore-search (&rest
1809 &key backend create delete label
1810 type max host user port
1812 "Search the PLSTORE; spec is like `auth-source'."
1813 (let* ((store (oref backend data))
1814 (max (or max 5000)) ; sanity check: default to stop at 5K
1815 (ignored-keys '(:create :delete :max :backend :label :require :type))
1816 (search-keys (loop for i below (length spec) by 2
1817 unless (memq (nth i spec) ignored-keys)
1818 collect (nth i spec)))
1819 ;; build a search spec without the ignored keys
1820 ;; if a search key is nil or t (match anything), we skip it
1821 (search-spec (apply 'append (mapcar
1823 (let ((v (plist-get spec k)))
1831 ;; needed keys (always including host, login, port, and secret)
1832 (returned-keys (mm-delete-duplicates (append
1833 '(:host :login :port :secret)
1835 (items (plstore-find store search-spec))
1836 (item-names (mapcar #'car items))
1837 (items (butlast items (- (length items) max)))
1838 ;; convert the item to a full plist
1839 (items (mapcar (lambda (item)
1840 (let* ((plist (copy-tree (cdr item)))
1841 (secret (plist-member plist :secret)))
1845 (lexical-let ((v (car (cdr secret))))
1849 ;; ensure each item has each key in `returned-keys'
1850 (items (mapcar (lambda (plist)
1853 (mapcar (lambda (req)
1854 (if (plist-get plist req)
1861 ;; if we need to create an entry AND none were found to match
1865 ;; create based on the spec and record the value
1867 ;; if the user did not want to create the entry
1868 ;; in the file, it will be returned
1869 (apply (slot-value backend 'create-function) spec)
1870 ;; if not, we do the search again without :create
1871 ;; to get the updated data.
1873 ;; the result will be returned, even if the search fails
1874 (apply 'auth-source-plstore-search
1875 (plist-put spec :create nil)))))
1878 (dolist (item-name item-names)
1879 (plstore-delete store item-name))
1880 (plstore-save store)))
1883 (defun* auth-source-plstore-create (&rest spec
1885 secret host user port create
1887 (let* ((base-required '(host user port secret))
1888 (base-secret '(secret))
1889 ;; we know (because of an assertion in auth-source-search) that the
1890 ;; :create parameter is either t or a list (which includes nil)
1891 (create-extra (if (eq t create) nil create))
1892 (current-data (car (auth-source-search :max 1
1895 (required (append base-required create-extra))
1896 (file (oref backend source))
1898 ;; `valist' is an alist
1900 ;; `artificial' will be returned if no creation is needed
1904 ;; only for base required elements (defined as function parameters):
1905 ;; fill in the valist with whatever data we may have from the search
1906 ;; we complete the first value if it's a list and use the value otherwise
1907 (dolist (br base-required)
1908 (when (symbol-value br)
1909 (let ((br-choice (cond
1910 ;; all-accepting choice (predicate is t)
1911 ((eq t (symbol-value br)) nil)
1912 ;; just the value otherwise
1913 (t (symbol-value br)))))
1915 (auth-source--aput valist br br-choice)))))
1917 ;; for extra required elements, see if the spec includes a value for them
1918 (dolist (er create-extra)
1919 (let ((name (concat ":" (symbol-name er)))
1920 (keys (loop for i below (length spec) by 2
1921 collect (nth i spec))))
1923 (when (equal (symbol-name k) name)
1924 (auth-source--aput valist er (plist-get spec k))))))
1926 ;; for each required element
1927 (dolist (r required)
1928 (let* ((data (auth-source--aget valist r))
1929 ;; take the first element if the data is a list
1930 (data (or (auth-source-netrc-element-or-first data)
1931 (plist-get current-data
1932 (intern (format ":%s" r) obarray))))
1933 ;; this is the default to be offered
1934 (given-default (auth-source--aget
1935 auth-source-creation-defaults r))
1936 ;; the default supplementals are simple:
1937 ;; for the user, try `given-default' and then (user-login-name);
1938 ;; otherwise take `given-default'
1940 ((and (not given-default) (eq r 'user))
1943 (printable-defaults (list
1946 (auth-source-netrc-element-or-first
1947 (auth-source--aget valist 'user))
1948 (plist-get artificial :user)
1952 (auth-source-netrc-element-or-first
1953 (auth-source--aget valist 'host))
1954 (plist-get artificial :host)
1958 (auth-source-netrc-element-or-first
1959 (auth-source--aget valist 'port))
1960 (plist-get artificial :port)
1962 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1964 (secret "%p password for %u@%h: ")
1965 (user "%p user name for %h: ")
1966 (host "%p host name for user %u: ")
1967 (port "%p port for %u@%h: "))
1968 (format "Enter %s (%%u@%%h:%%p): " r)))
1969 (prompt (auth-source-format-prompt
1971 `((?u ,(auth-source--aget printable-defaults 'user))
1972 (?h ,(auth-source--aget printable-defaults 'host))
1973 (?p ,(auth-source--aget printable-defaults 'port))))))
1975 ;; Store the data, prompting for the password if needed.
1978 (or (eval default) (read-passwd prompt))
1979 (if (stringp default)
1981 (if (string-match ": *\\'" prompt)
1982 (concat (substring prompt 0 (match-beginning 0))
1983 " (default " default "): ")
1984 (concat prompt "(default " default ") "))
1989 (if (member r base-secret)
1990 (setq secret-artificial
1991 (plist-put secret-artificial
1992 (intern (concat ":" (symbol-name r)))
1994 (setq artificial (plist-put artificial
1995 (intern (concat ":" (symbol-name r)))
1997 (plstore-put (oref backend data)
1998 (sha1 (format "%s@%s:%s"
1999 (plist-get artificial :user)
2000 (plist-get artificial :host)
2001 (plist-get artificial :port)))
2002 artificial secret-artificial)
2003 (if (y-or-n-p (format "Save auth info to file %s? "
2004 (plstore-get-file (oref backend data))))
2005 (plstore-save (oref backend data)))))
2009 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2011 ;; deprecate the old interface
2012 (make-obsolete 'auth-source-user-or-password
2013 'auth-source-search "Emacs 24.1")
2014 (make-obsolete 'auth-source-forget-user-or-password
2015 'auth-source-forget "Emacs 24.1")
2017 (defun auth-source-user-or-password
2018 (mode host port &optional username create-missing delete-existing)
2019 "Find MODE (string or list of strings) matching HOST and PORT.
2021 DEPRECATED in favor of `auth-source-search'!
2023 USERNAME is optional and will be used as \"login\" in a search
2024 across the Secret Service API (see secrets.el) if the resulting
2025 items don't have a username. This means that if you search for
2026 username \"joe\" and it matches an item but the item doesn't have
2027 a :user attribute, the username \"joe\" will be returned.
2029 A non nil DELETE-EXISTING means deleting any matching password
2030 entry in the respective sources. This is useful only when
2031 CREATE-MISSING is non nil as well; the intended use case is to
2032 remove wrong password entries.
2034 If no matching entry is found, and CREATE-MISSING is non nil,
2035 the password will be retrieved interactively, and it will be
2036 stored in the password database which matches best (see
2039 MODE can be \"login\" or \"password\"."
2040 (auth-source-do-debug
2041 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2042 mode host port username)
2044 (let* ((listy (listp mode))
2045 (mode (if listy mode (list mode)))
2047 (format "%s %s:%s %s" mode host port username)
2048 (format "%s %s:%s" mode host port)))
2049 (search (list :host host :port port))
2050 (search (if username (append search (list :user username)) search))
2051 (search (if create-missing
2052 (append search (list :create t))
2054 (search (if delete-existing
2055 (append search (list :delete t))
2057 ;; (found (if (not delete-existing)
2058 ;; (gethash cname auth-source-cache)
2059 ;; (remhash cname auth-source-cache)
2064 (auth-source-do-debug
2065 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2067 ;; don't show the password
2068 (if (and (member "password" mode) t)
2072 found) ; return the found data
2073 ;; else, if not found, search with a max of 1
2074 (let ((choice (nth 0 (apply 'auth-source-search
2075 (append '(:max 1) search)))))
2079 ((equal "password" m)
2080 (push (if (plist-get choice :secret)
2081 (funcall (plist-get choice :secret))
2084 (push (plist-get choice :user) found)))))
2085 (setq found (nreverse found))
2086 (setq found (if listy found (car-safe found)))))
2090 (defun auth-source-user-and-password (host &optional user)
2091 (let* ((auth-info (car
2095 :user "yourusername"
2097 :require '(:user :secret)
2102 :require '(:user :secret)
2104 (user (plist-get auth-info :user))
2105 (password (plist-get auth-info :secret)))
2106 (when (functionp password)
2107 (setq password (funcall password)))
2108 (list user password auth-info)))
2110 (provide 'auth-source)
2112 ;;; auth-source.el ends here