1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2012 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)
47 (eval-when-compile (require 'cl))
49 (or (ignore-errors (require 'eieio))
50 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
52 (let ((load-path (cons (expand-file-name
53 "gnus-fallback-lib/eieio"
54 (file-name-directory (locate-library "gnus")))
58 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
60 (autoload 'secrets-create-item "secrets")
61 (autoload 'secrets-delete-item "secrets")
62 (autoload 'secrets-get-alias "secrets")
63 (autoload 'secrets-get-attributes "secrets")
64 (autoload 'secrets-get-secret "secrets")
65 (autoload 'secrets-list-collections "secrets")
66 (autoload 'secrets-search-items "secrets")
68 (autoload 'rfc2104-hash "rfc2104")
70 (autoload 'plstore-open "plstore")
71 (autoload 'plstore-find "plstore")
72 (autoload 'plstore-put "plstore")
73 (autoload 'plstore-delete "plstore")
74 (autoload 'plstore-save "plstore")
75 (autoload 'plstore-get-file "plstore")
77 (autoload 'epg-make-context "epg")
78 (autoload 'epg-context-set-passphrase-callback "epg")
79 (autoload 'epg-decrypt-string "epg")
80 (autoload 'epg-context-set-armor "epg")
81 (autoload 'epg-encrypt-string "epg")
83 (autoload 'help-mode "help-mode" nil t)
85 (defvar secrets-enabled)
87 (defgroup auth-source nil
88 "Authentication sources."
89 :version "23.1" ;; No Gnus
93 (defcustom auth-source-cache-expiry 7200
94 "How many seconds passwords are cached, or nil to disable
95 expiring. Overrides `password-cache-expiry' through a
99 :type '(choice (const :tag "Never" nil)
100 (const :tag "All Day" 86400)
101 (const :tag "2 Hours" 7200)
102 (const :tag "30 Minutes" 1800)
103 (integer :tag "Seconds")))
105 ;;; The slots below correspond with the `auth-source-search' spec,
106 ;;; so a backend with :host set, for instance, would match only
107 ;;; searches for that host. Normally they are nil.
108 (defclass auth-source-backend ()
109 ((type :initarg :type
113 :documentation "The backend type.")
114 (source :initarg :source
117 :documentation "The backend source.")
122 :documentation "The backend host.")
127 :documentation "The backend user.")
132 :documentation "The backend protocol.")
135 :documentation "Internal backend data.")
136 (create-function :initarg :create-function
140 :documentation "The create function.")
141 (search-function :initarg :search-function
145 :documentation "The search function.")))
147 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
148 (pop3 "pop3" "pop" "pop3s" "110" "995")
152 "List of authentication protocols and their names"
155 :version "23.2" ;; No Gnus
156 :type '(repeat :tag "Authentication Protocols"
157 (cons :tag "Protocol Entry"
158 (symbol :tag "Protocol")
160 (string :tag "Name")))))
162 ;;; generate all the protocols in a format Customize can use
163 ;;; TODO: generate on the fly from auth-source-protocols
164 (defconst auth-source-protocols-customize
166 (let ((p (car-safe a)))
168 :tag (upcase (symbol-name p))
170 auth-source-protocols))
172 (defvar auth-source-creation-defaults nil
173 "Defaults for creating token values. Usually let-bound.")
175 (defvar auth-source-creation-prompts nil
176 "Default prompts for token values. Usually let-bound.")
178 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
180 (defcustom auth-source-save-behavior 'ask
181 "If set, auth-source will respect it for save behavior."
183 :version "23.2" ;; No Gnus
185 :tag "auth-source new token save behavior"
186 (const :tag "Always save" t)
187 (const :tag "Never save" nil)
188 (const :tag "Ask" ask)))
190 ;; 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)))
191 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
193 (defcustom auth-source-netrc-use-gpg-tokens 'never
194 "Set this to tell auth-source when to create GPG password
195 tokens in netrc files. It's either an alist or `never'.
196 Note that if EPA/EPG is not available, this should NOT be used."
198 :version "23.2" ;; No Gnus
200 (const :tag "Always use GPG password tokens" (t gpg))
201 (const :tag "Never use GPG password tokens" never)
202 (repeat :tag "Use a lookup list"
204 (choice :tag "Matcher"
205 (const :tag "Match anything" t)
206 (const :tag "The EPA encrypted file extensions"
207 ,(if (boundp 'epa-file-auto-mode-alist-entry)
209 'epa-file-auto-mode-alist-entry))
211 (regexp :tag "Regular expression"))
212 (choice :tag "What to do"
213 (const :tag "Save GPG-encrypted password tokens" gpg)
214 (const :tag "Don't encrypt tokens" never))))))
216 (defvar auth-source-magic "auth-source-magic ")
218 (defcustom auth-source-do-cache t
219 "Whether auth-source should cache information with `password-cache'."
221 :version "23.2" ;; No Gnus
224 (defcustom auth-source-debug nil
225 "Whether auth-source should log debug messages.
227 If the value is nil, debug messages are not logged.
229 If the value is t, debug messages are logged with `message'. In
230 that case, your authentication data will be in the clear (except
233 If the value is a function, debug messages are logged by calling
234 that function using the same arguments as `message'."
236 :version "23.2" ;; No Gnus
238 :tag "auth-source debugging mode"
239 (const :tag "Log using `message' to the *Messages* buffer" t)
240 (const :tag "Log all trivia with `message' to the *Messages* buffer"
242 (function :tag "Function that takes arguments like `message'")
243 (const :tag "Don't log anything" nil)))
245 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
246 "List of authentication sources.
248 The default will get login and password information from
249 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
250 packages to be encrypted. If that file doesn't exist, it will
251 try the unencrypted version \"~/.authinfo\" and the famous
254 See the auth.info manual for details.
256 Each entry is the authentication type with optional properties.
258 It's best to customize this with `M-x customize-variable' because the choices
259 can get pretty complex."
261 :version "24.1" ;; No Gnus
262 :type `(repeat :tag "Authentication Sources"
264 (string :tag "Just a file")
265 (const :tag "Default Secrets API Collection" 'default)
266 (const :tag "Login Secrets API Collection" "secrets:Login")
267 (const :tag "Temp Secrets API Collection" "secrets:session")
268 (list :tag "Source definition"
269 (const :format "" :value :source)
270 (choice :tag "Authentication backend choice"
271 (string :tag "Authentication Source (file)")
273 :tag "Secret Service API/KWallet/GNOME Keyring"
274 (const :format "" :value :secrets)
275 (choice :tag "Collection to use"
276 (string :tag "Collection name")
277 (const :tag "Default" 'default)
278 (const :tag "Login" "Login")
280 :tag "Temporary" "session"))))
281 (repeat :tag "Extra Parameters" :inline t
282 (choice :tag "Extra parameter"
285 (const :format "" :value :host)
286 (choice :tag "Host (machine) choice"
289 :tag "Regular expression")))
292 (const :format "" :value :port)
296 ,@auth-source-protocols-customize))
297 (list :tag "User" :inline t
298 (const :format "" :value :user)
300 :tag "Personality/Username"
305 (defcustom auth-source-gpg-encrypt-to t
306 "List of recipient keys that `authinfo.gpg' encrypted to.
307 If the value is not a list, symmetric encryption will be used."
309 :version "24.1" ;; No Gnus
310 :type '(choice (const :tag "Symmetric encryption" t)
311 (repeat :tag "Recipient public keys"
312 (string :tag "Recipient public key"))))
314 ;; temp for debugging
315 ;; (unintern 'auth-source-protocols)
316 ;; (unintern 'auth-sources)
317 ;; (customize-variable 'auth-sources)
318 ;; (setq auth-sources nil)
319 ;; (format "%S" auth-sources)
320 ;; (customize-variable 'auth-source-protocols)
321 ;; (setq auth-source-protocols nil)
322 ;; (format "%S" auth-source-protocols)
323 ;; (auth-source-pick nil :host "a" :port 'imap)
324 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
325 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
326 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
327 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
328 ;; (auth-source-protocol-defaults 'imap)
330 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
331 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
332 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
333 (defun auth-source-do-debug (&rest msg)
334 (when auth-source-debug
335 (apply 'auth-source-do-warn msg)))
337 (defun auth-source-do-trivia (&rest msg)
338 (when (or (eq auth-source-debug 'trivia)
339 (functionp auth-source-debug))
340 (apply 'auth-source-do-warn msg)))
342 (defun auth-source-do-warn (&rest msg)
344 ;; set logger to either the function in auth-source-debug or 'message
345 ;; note that it will be 'message if auth-source-debug is nil
346 (if (functionp auth-source-debug)
352 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
353 (defun auth-source-read-char-choice (prompt choices)
354 "Read one of CHOICES by `read-char-choice', or `read-char'.
355 `dropdown-list' support is disabled because it doesn't work reliably.
356 Only one of CHOICES will be returned. The PROMPT is augmented
357 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
359 (let* ((prompt-choices
360 (apply 'concat (loop for c in choices
361 collect (format "%c/" c))))
362 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
363 (full-prompt (concat prompt prompt-choices))
366 (while (not (memq k choices))
368 ((fboundp 'read-char-choice)
369 (read-char-choice full-prompt choices))
370 (t (message "%s" full-prompt)
371 (setq k (read-char))))))
374 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
375 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
376 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
377 ;; (:source (:secrets "session") :host t :port t :user "joe")
378 ;; (:source (:secrets "Login") :host t :port t)
379 ;; (:source "~/.authinfo.gpg" :host t :port t)))
381 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
382 ;; (:source (:secrets "session") :host t :port t :user "joe")
383 ;; (:source (:secrets "Login") :host t :port t)
386 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
388 ;; (auth-source-backend-parse "myfile.gpg")
389 ;; (auth-source-backend-parse 'default)
390 ;; (auth-source-backend-parse "secrets:Login")
392 (defun auth-source-backend-parse (entry)
393 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
394 (auth-source-backend-parse-parameters
397 ;; take 'default and recurse to get it as a Secrets API default collection
398 ;; matching any user, host, and protocol
400 (auth-source-backend-parse '(:source (:secrets default))))
401 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
402 ;; matching any user, host, and protocol
403 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
404 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
405 ;; take just a file name and recurse to get it as a netrc file
406 ;; matching any user, host, and protocol
408 (auth-source-backend-parse `(:source ,entry)))
410 ;; a file name with parameters
411 ((stringp (plist-get entry :source))
412 (if (equal (file-name-extension (plist-get entry :source)) "plist")
414 (plist-get entry :source)
415 :source (plist-get entry :source)
417 :search-function 'auth-source-plstore-search
418 :create-function 'auth-source-plstore-create
419 :data (plstore-open (plist-get entry :source)))
421 (plist-get entry :source)
422 :source (plist-get entry :source)
424 :search-function 'auth-source-netrc-search
425 :create-function 'auth-source-netrc-create)))
427 ;; the Secrets API. We require the package, in order to have a
428 ;; defined value for `secrets-enabled'.
430 (not (null (plist-get entry :source))) ; the source must not be nil
431 (listp (plist-get entry :source)) ; and it must be a list
432 (require 'secrets nil t) ; and we must load the Secrets API
433 secrets-enabled) ; and that API must be enabled
435 ;; the source is either the :secrets key in ENTRY or
436 ;; if that's missing or nil, it's "session"
437 (let ((source (or (plist-get (plist-get entry :source) :secrets)
440 ;; if the source is a symbol, we look for the alias named so,
441 ;; and if that alias is missing, we use "Login"
442 (when (symbolp source)
443 (setq source (or (secrets-get-alias (symbol-name source))
446 (if (featurep 'secrets)
448 (format "Secrets API (%s)" source)
451 :search-function 'auth-source-secrets-search
452 :create-function 'auth-source-secrets-create)
454 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
456 (format "Ignored Secrets API (%s)" source)
463 "auth-source-backend-parse: invalid backend spec: %S" entry)
469 (defun auth-source-backend-parse-parameters (entry backend)
470 "Fills in the extra auth-source-backend parameters of ENTRY.
471 Using the plist ENTRY, get the :host, :port, and :user search
473 (let ((entry (if (stringp entry)
477 (when (setq val (plist-get entry :host))
478 (oset backend host val))
479 (when (setq val (plist-get entry :user))
480 (oset backend user val))
481 (when (setq val (plist-get entry :port))
482 (oset backend port val)))
485 ;; (mapcar 'auth-source-backend-parse auth-sources)
487 (defun* auth-source-search (&rest spec
488 &key type max host user port secret
489 require create delete
491 "Search or modify authentication backends according to SPEC.
493 This function parses `auth-sources' for matches of the SPEC
494 plist. It can optionally create or update an authentication
495 token if requested. A token is just a standard Emacs property
496 list with a :secret property that can be a function; all the
497 other properties will always hold scalar values.
499 Typically the :secret property, if present, contains a password.
501 Common search keys are :max, :host, :port, and :user. In
502 addition, :create specifies how tokens will be or created.
503 Finally, :type can specify which backend types you want to check.
505 A string value is always matched literally. A symbol is matched
506 as its string value, literally. All the SPEC values can be
507 single values (symbol or string) or lists thereof (in which case
508 any of the search terms matches).
510 :create t means to create a token if possible.
512 A new token will be created if no matching tokens were found.
513 The new token will have only the keys the backend requires. For
514 the netrc backend, for instance, that's the user, host, and
519 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
520 (A . \"default A\"))))
521 (auth-source-search :host \"mine\" :type 'netrc :max 1
522 :P \"pppp\" :Q \"qqqq\"
527 \"Search for any entry matching host 'mine' in backends of type
528 'netrc', maximum one result.
530 Create a new entry if you found none. The netrc backend will
531 automatically require host, user, and port. The host will be
532 'mine'. We prompt for the user with default 'defaultUser' and
533 for the port without a default. We will not prompt for A, Q,
534 or P. The resulting token will only have keys user, host, and
537 :create '(A B C) also means to create a token if possible.
539 The behavior is like :create t but if the list contains any
540 parameter, that parameter will be required in the resulting
541 token. The value for that parameter will be obtained from the
542 search parameters or from user input. If any queries are needed,
543 the alist `auth-source-creation-defaults' will be checked for the
544 default value. If the user, host, or port are missing, the alist
545 `auth-source-creation-prompts' will be used to look up the
546 prompts IN THAT ORDER (so the 'user prompt will be queried first,
547 then 'host, then 'port, and finally 'secret). Each prompt string
548 can use %u, %h, and %p to show the user, host, and port.
552 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
553 (A . \"default A\")))
554 (auth-source-creation-prompts
555 '((password . \"Enter IMAP password for %h:%p: \"))))
556 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
557 :P \"pppp\" :Q \"qqqq\"
562 \"Search for any entry matching host 'nonesuch'
563 or 'twosuch' in backends of type 'netrc', maximum one result.
565 Create a new entry if you found none. The netrc backend will
566 automatically require host, user, and port. The host will be
567 'nonesuch' and Q will be 'qqqq'. We prompt for the password
568 with the shown prompt. We will not prompt for Q. The resulting
569 token will have keys user, host, port, A, B, and Q. It will not
570 have P with any value, even though P is used in the search to
571 find only entries that have P set to 'pppp'.\"
573 When multiple values are specified in the search parameter, the
574 user is prompted for which one. So :host (X Y Z) would ask the
575 user to choose between X, Y, and Z.
577 This creation can fail if the search was not specific enough to
578 create a new token (it's up to the backend to decide that). You
579 should `catch' the backend-specific error as usual. Some
580 backends (netrc, at least) will prompt the user rather than throw
583 :require (A B C) means that only results that contain those
584 tokens will be returned. Thus for instance requiring :secret
585 will ensure that any results will actually have a :secret
588 :delete t means to delete any found entries. nil by default.
589 Use `auth-source-delete' in ELisp code instead of calling
590 `auth-source-search' directly with this parameter.
592 :type (X Y Z) will check only those backend types. 'netrc and
593 'secrets are the only ones supported right now.
595 :max N means to try to return at most N items (defaults to 1).
596 When 0 the function will return just t or nil to indicate if any
597 matches were found. More than N items may be returned, depending
598 on the search and the backend.
600 :host (X Y Z) means to match only hosts X, Y, or Z according to
601 the match rules above. Defaults to t.
603 :user (X Y Z) means to match only users X, Y, or Z according to
604 the match rules above. Defaults to t.
606 :port (P Q R) means to match only protocols P, Q, or R.
609 :K (V1 V2 V3) for any other key K will match values V1, V2, or
610 V3 (note the match rules above).
612 The return value is a list with at most :max tokens. Each token
613 is a plist with keys :backend :host :port :user, plus any other
614 keys provided by the backend (notably :secret). But note the
615 exception for :max 0, which see above.
617 The token can hold a :save-function key. If you call that, the
618 user will be prompted to save the data to the backend. You can't
619 request that this should happen right after creation, because
620 `auth-source-search' has no way of knowing if the token is
621 actually useful. So the caller must arrange to call this function.
623 The token's :secret key can hold a function. In that case you
624 must call it to obtain the actual value."
625 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
627 (ignored-keys '(:require :create :delete :max))
628 (keys (loop for i below (length spec) by 2
629 unless (memq (nth i spec) ignored-keys)
630 collect (nth i spec)))
631 (cached (auth-source-remembered-p spec))
632 ;; note that we may have cached results but found is still nil
633 ;; (there were no results from the search)
634 (found (auth-source-recall spec))
635 filtered-backends accessor-key backend)
637 (if (and cached auth-source-do-cache)
638 (auth-source-do-debug
639 "auth-source-search: found %d CACHED results matching %S"
643 (or (eq t create) (listp create)) t
644 "Invalid auth-source :create parameter (must be t or a list): %s %s")
648 "Invalid auth-source :require parameter (must be a list): %s")
650 (setq filtered-backends (copy-sequence backends))
651 (dolist (backend backends)
653 ;; ignore invalid slots
654 (condition-case signal
655 (unless (eval `(auth-source-search-collection
657 (oref backend ,key)))
658 (setq filtered-backends (delq backend filtered-backends))
660 (invalid-slot-name))))
662 (auth-source-do-trivia
663 "auth-source-search: found %d backends matching %S"
664 (length filtered-backends) spec)
666 ;; (debug spec "filtered" filtered-backends)
667 ;; First go through all the backends without :create, so we can
669 (setq found (auth-source-search-backends filtered-backends
673 ;; create is always nil here
677 (auth-source-do-debug
678 "auth-source-search: found %d results (max %d) matching %S"
679 (length found) max spec)
681 ;; If we didn't find anything, then we allow the backend(s) to
682 ;; create the entries.
685 (setq found (auth-source-search-backends filtered-backends
691 (auth-source-do-debug
692 "auth-source-search: CREATED %d results (max %d) matching %S"
693 (length found) max spec))
695 ;; note we remember the lack of result too, if it's applicable
696 (when auth-source-do-cache
697 (auth-source-remember spec found)))
701 (defun auth-source-search-backends (backends spec max create delete require)
703 (dolist (backend backends)
704 (when (> max (length matches)) ; when we need more matches...
705 (let* ((bmatches (apply
706 (slot-value backend 'search-function)
708 ;; note we're overriding whatever the spec
709 ;; has for :require, :create, and :delete
715 (auth-source-do-trivia
716 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
717 (length bmatches) max
718 (slot-value backend :type)
719 (slot-value backend :source)
721 (setq matches (append matches bmatches))))))
724 ;;; (auth-source-search :max 1)
725 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
726 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
727 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
729 (defun* auth-source-delete (&rest spec
732 "Delete entries from the authentication backends according to SPEC.
733 Calls `auth-source-search' with the :delete property in SPEC set to t.
734 The backend may not actually delete the entries.
736 Returns the deleted entries."
737 (auth-source-search (plist-put spec :delete t)))
739 (defun auth-source-search-collection (collection value)
740 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
741 (when (and (atom collection) (not (eq t collection)))
742 (setq collection (list collection)))
744 ;; (debug :collection collection :value value)
745 (or (eq collection t)
747 (equal collection value)
748 (member value collection)))
750 (defvar auth-source-netrc-cache nil)
752 (defun auth-source-forget-all-cached ()
753 "Forget all cached auth-source data."
755 (loop for sym being the symbols of password-data
756 ;; when the symbol name starts with auth-source-magic
757 when (string-match (concat "^" auth-source-magic)
760 do (password-cache-remove (symbol-name sym)))
761 (setq auth-source-netrc-cache nil))
763 (defun auth-source-format-cache-entry (spec)
764 "Format SPEC entry to put it in the password cache."
765 (concat auth-source-magic (format "%S" spec)))
767 (defun auth-source-remember (spec found)
768 "Remember FOUND search results for SPEC."
769 (let ((password-cache-expiry auth-source-cache-expiry))
771 (auth-source-format-cache-entry spec) found)))
773 (defun auth-source-recall (spec)
774 "Recall FOUND search results for SPEC."
775 (password-read-from-cache (auth-source-format-cache-entry spec)))
777 (defun auth-source-remembered-p (spec)
778 "Check if SPEC is remembered."
780 (auth-source-format-cache-entry spec)))
782 (defun auth-source-forget (spec)
783 "Forget any cached data matching SPEC exactly.
785 This is the same SPEC you passed to `auth-source-search'.
786 Returns t or nil for forgotten or not found."
787 (password-cache-remove (auth-source-format-cache-entry spec)))
789 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
791 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
792 ;;; (auth-source-remembered-p '(:host "wedd"))
793 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
794 ;;; (auth-source-remembered-p '(:host "xedd"))
795 ;;; (auth-source-remembered-p '(:host "zedd"))
796 ;;; (auth-source-recall '(:host "xedd"))
797 ;;; (auth-source-recall '(:host t))
798 ;;; (auth-source-forget+ :host t)
800 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
801 "Forget any cached data matching SPEC. Returns forgotten count.
803 This is not a full `auth-source-search' spec but works similarly.
804 For instance, \(:host \"myhost\" \"yourhost\") would find all the
805 cached data that was found with a search for those two hosts,
806 while \(:host t) would find all host entries."
809 (loop for sym being the symbols of password-data
810 ;; when the symbol name matches with auth-source-magic
811 when (and (setq sname (symbol-name sym))
812 (string-match (concat "^" auth-source-magic "\\(.+\\)")
814 ;; and the spec matches what was stored in the cache
815 (auth-source-specmatchp spec (read (match-string 1 sname))))
818 (password-cache-remove sname)
822 (defun auth-source-specmatchp (spec stored)
823 (let ((keys (loop for i below (length spec) by 2
824 collect (nth i spec))))
827 (unless (auth-source-search-collection (plist-get stored key)
828 (plist-get spec key))
832 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
833 ;;; (auth-source-pick-first-password :port "imap")
834 (defun auth-source-pick-first-password (&rest spec)
835 "Pick the first secret found from applying SPEC to `auth-source-search'."
836 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
837 (secret (plist-get result :secret)))
839 (if (functionp secret)
843 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
844 (defun auth-source-format-prompt (prompt alist)
845 "Format PROMPT using %x (for any character x) specifiers in ALIST."
847 (let ((c (nth 0 cell))
850 (setq prompt (replace-regexp-in-string (format "%%%c" c)
855 (defun auth-source-ensure-strings (values)
856 (unless (listp values)
857 (setq values (list values)))
858 (mapcar (lambda (value)
864 ;;; Backend specific parsing: netrc/authinfo backend
866 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
867 (defun* auth-source-netrc-parse (&rest
869 &key file max host user port delete require
871 "Parse FILE and return a list of all entries in the file.
872 Note that the MAX parameter is used so we can exit the parse early."
874 ;; We got already parsed contents; just return it.
876 (when (file-exists-p file)
877 (setq port (auth-source-ensure-strings port))
879 (let* ((tokens '("machine" "host" "default" "login" "user"
880 "password" "account" "macdef" "force"
882 (max (or max 5000)) ; sanity check: default to stop at 5K
884 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
885 (cached-mtime (plist-get cached :mtime))
886 (cached-secrets (plist-get cached :secret))
887 alist elem result pair)
889 (if (and (functionp cached-secrets)
891 (nth 5 (file-attributes file))))
893 (auth-source-do-trivia
894 "auth-source-netrc-parse: using CACHED file data for %s"
896 (insert (funcall cached-secrets)))
897 (insert-file-contents file)
898 ;; cache all netrc files (used to be just .gpg files)
899 ;; Store the contents of the file heavily encrypted in memory.
900 ;; (note for the irony-impaired: they are just obfuscated)
901 (aput 'auth-source-netrc-cache file
902 (list :mtime (nth 5 (file-attributes file))
903 :secret (lexical-let ((v (mapcar '1+ (buffer-string))))
904 (lambda () (apply 'string (mapcar '1- v)))))))
905 (goto-char (point-min))
906 ;; Go through the file, line by line.
907 (while (and (not (eobp))
910 (narrow-to-region (point) (point-at-eol))
911 ;; For each line, get the tokens and values.
913 (skip-chars-forward "\t ")
914 ;; Skip lines that begin with a "#".
915 (if (eq (char-after) ?#)
916 (goto-char (point-max))
919 (if (= (following-char) ?\")
920 (read (current-buffer))
922 (point) (progn (skip-chars-forward "^\t ")
925 ((equal elem "macdef")
926 ;; We skip past the macro definition.
928 (while (and (zerop (forward-line 1))
930 (narrow-to-region (point) (point)))
931 ((member elem tokens)
932 ;; Tokens that don't have a following value are ignored,
934 (when (and pair (or (cdr pair)
935 (equal (car pair) "default")))
937 (setq pair (list elem)))
939 ;; Values that haven't got a preceding token are ignored.
943 (setq pair nil)))))))
947 (auth-source-search-collection
950 (aget alist "machine")
953 (auth-source-search-collection
957 (aget alist "account")
960 (auth-source-search-collection
964 (aget alist "protocol")
967 ;; the required list of keys is nil, or
969 ;; every element of require is in the normalized list
970 (let ((normalized (nth 0 (auth-source-netrc-normalize
971 (list alist) file))))
972 (loop for req in require
973 always (plist-get normalized req)))))
975 (push (nreverse alist) result)
976 ;; to delete a line, we just comment it out
978 (goto-char (point-min))
987 (when auth-source-gpg-encrypt-to
988 ;; (see bug#7487) making `epa-file-encrypt-to' local to
989 ;; this buffer lets epa-file skip the key selection query
990 ;; (see the `local-variable-p' check in
991 ;; `epa-file-write-region').
992 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
993 (make-local-variable 'epa-file-encrypt-to))
994 (if (listp auth-source-gpg-encrypt-to)
995 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
997 ;; ask AFTER we've successfully opened the file
998 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1000 (write-region (point-min) (point-max) file nil 'silent)
1001 (auth-source-do-debug
1002 "auth-source-netrc-parse: modified %d lines in %s"
1005 (nreverse result))))))
1007 (defvar auth-source-passphrase-alist nil)
1009 (defun auth-source-token-passphrase-callback-function (context key-id file)
1010 (let* ((file (file-truename file))
1011 (entry (assoc file auth-source-passphrase-alist))
1013 ;; return the saved passphrase, calling a function if needed
1014 (or (copy-sequence (if (functionp (cdr entry))
1015 (funcall (cdr entry))
1019 (setq entry (list file))
1020 (push entry auth-source-passphrase-alist))
1023 (format "Passphrase for %s tokens: " file)
1025 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1029 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1030 (defun auth-source-epa-extract-gpg-token (secret file)
1031 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1032 FILE is the file from which we obtained this token."
1033 (when (string-match "^gpg:\\(.+\\)" secret)
1034 (setq secret (base64-decode-string (match-string 1 secret))))
1035 (let ((context (epg-make-context 'OpenPGP))
1037 (epg-context-set-passphrase-callback
1039 (cons #'auth-source-token-passphrase-callback-function
1041 (epg-decrypt-string context secret)))
1043 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1044 (defun auth-source-epa-make-gpg-token (secret file)
1045 (let ((context (epg-make-context 'OpenPGP))
1046 (pp-escape-newlines nil)
1048 (epg-context-set-armor context t)
1049 (epg-context-set-passphrase-callback
1051 (cons #'auth-source-token-passphrase-callback-function
1053 (setq cipher (epg-encrypt-string context secret nil))
1056 (base64-encode-region (point-min) (point-max) t)
1057 (concat "gpg:" (buffer-substring-no-properties
1061 (defun auth-source-netrc-normalize (alist filename)
1062 (mapcar (lambda (entry)
1064 (while (setq item (pop entry))
1065 (let ((k (car item))
1068 ;; apply key aliases
1069 (setq k (cond ((member k '("machine")) "host")
1070 ((member k '("login" "account")) "user")
1071 ((member k '("protocol")) "port")
1072 ((member k '("password")) "secret")
1075 ;; send back the secret in a function (lexical binding)
1076 (when (equal k "secret")
1077 (setq v (lexical-let ((lexv v)
1078 (token-decoder nil))
1079 (when (string-match "^gpg:" lexv)
1080 ;; it's a GPG token: create a token decoder
1081 ;; which unsets itself once
1085 (auth-source-epa-extract-gpg-token
1088 (setq token-decoder nil)))))
1091 (setq lexv (funcall token-decoder lexv)))
1093 (setq ret (plist-put ret
1094 (intern (concat ":" k))
1099 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1100 ;;; (funcall secret)
1102 (defun* auth-source-netrc-search (&rest
1104 &key backend require create delete
1105 type max host user port
1107 "Given a property list SPEC, return search matches from the :backend.
1108 See `auth-source-search' for details on SPEC."
1109 ;; just in case, check that the type is correct (null or same as the backend)
1110 (assert (or (null type) (eq type (oref backend type)))
1111 t "Invalid netrc search: %s %s")
1113 (let ((results (auth-source-netrc-normalize
1114 (auth-source-netrc-parse
1118 :file (oref backend source)
1122 (oref backend source))))
1124 ;; if we need to create an entry AND none were found to match
1128 ;; create based on the spec and record the value
1130 ;; if the user did not want to create the entry
1131 ;; in the file, it will be returned
1132 (apply (slot-value backend 'create-function) spec)
1133 ;; if not, we do the search again without :create
1134 ;; to get the updated data.
1136 ;; the result will be returned, even if the search fails
1137 (apply 'auth-source-netrc-search
1138 (plist-put spec :create nil)))))
1141 (defun auth-source-netrc-element-or-first (v)
1146 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1147 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1149 (defun* auth-source-netrc-create (&rest spec
1151 secret host user port create
1153 (let* ((base-required '(host user port secret))
1154 ;; we know (because of an assertion in auth-source-search) that the
1155 ;; :create parameter is either t or a list (which includes nil)
1156 (create-extra (if (eq t create) nil create))
1157 (current-data (car (auth-source-search :max 1
1160 (required (append base-required create-extra))
1161 (file (oref backend source))
1163 ;; `valist' is an alist
1165 ;; `artificial' will be returned if no creation is needed
1168 ;; only for base required elements (defined as function parameters):
1169 ;; fill in the valist with whatever data we may have from the search
1170 ;; we complete the first value if it's a list and use the value otherwise
1171 (dolist (br base-required)
1172 (when (symbol-value br)
1173 (let ((br-choice (cond
1174 ;; all-accepting choice (predicate is t)
1175 ((eq t (symbol-value br)) nil)
1176 ;; just the value otherwise
1177 (t (symbol-value br)))))
1179 (aput 'valist br br-choice)))))
1181 ;; for extra required elements, see if the spec includes a value for them
1182 (dolist (er create-extra)
1183 (let ((name (concat ":" (symbol-name er)))
1184 (keys (loop for i below (length spec) by 2
1185 collect (nth i spec))))
1187 (when (equal (symbol-name k) name)
1188 (aput 'valist er (plist-get spec k))))))
1190 ;; for each required element
1191 (dolist (r required)
1192 (let* ((data (aget valist r))
1193 ;; take the first element if the data is a list
1194 (data (or (auth-source-netrc-element-or-first data)
1195 (plist-get current-data
1196 (intern (format ":%s" r) obarray))))
1197 ;; this is the default to be offered
1198 (given-default (aget auth-source-creation-defaults r))
1199 ;; the default supplementals are simple:
1200 ;; for the user, try `given-default' and then (user-login-name);
1201 ;; otherwise take `given-default'
1203 ((and (not given-default) (eq r 'user))
1206 (printable-defaults (list
1209 (auth-source-netrc-element-or-first
1210 (aget valist 'user))
1211 (plist-get artificial :user)
1215 (auth-source-netrc-element-or-first
1216 (aget valist 'host))
1217 (plist-get artificial :host)
1221 (auth-source-netrc-element-or-first
1222 (aget valist 'port))
1223 (plist-get artificial :port)
1225 (prompt (or (aget auth-source-creation-prompts r)
1227 (secret "%p password for %u@%h: ")
1228 (user "%p user name for %h: ")
1229 (host "%p host name for user %u: ")
1230 (port "%p port for %u@%h: "))
1231 (format "Enter %s (%%u@%%h:%%p): " r)))
1232 (prompt (auth-source-format-prompt
1234 `((?u ,(aget printable-defaults 'user))
1235 (?h ,(aget printable-defaults 'host))
1236 (?p ,(aget printable-defaults 'port))))))
1238 ;; Store the data, prompting for the password if needed.
1241 ;; Special case prompt for passwords.
1242 ;; 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)))
1243 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1244 (let* ((ep (format "Use GPG password tokens in %s?" file))
1247 ((eq auth-source-netrc-use-gpg-tokens 'never)
1249 ((listp auth-source-netrc-use-gpg-tokens)
1250 (let ((check (copy-sequence
1251 auth-source-netrc-use-gpg-tokens))
1254 (setq item (pop check))
1255 (when (or (eq (car item) t)
1256 (string-match (car item) file))
1257 (setq ret (cdr item))
1258 (setq check nil)))))
1260 (plain (or (eval default) (read-passwd prompt))))
1261 ;; ask if we don't know what to do (in which case
1262 ;; auth-source-netrc-use-gpg-tokens must be a list)
1264 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1265 ;; TODO: save the defcustom now? or ask?
1266 (setq auth-source-netrc-use-gpg-tokens
1267 (cons `(,file ,gpg-encrypt)
1268 auth-source-netrc-use-gpg-tokens)))
1269 (if (eq gpg-encrypt 'gpg)
1270 (auth-source-epa-make-gpg-token plain file)
1272 (if (stringp default)
1273 (read-string (if (string-match ": *\\'" prompt)
1274 (concat (substring prompt 0 (match-beginning 0))
1275 " (default " default "): ")
1276 (concat prompt "(default " default ") "))
1281 (setq artificial (plist-put artificial
1282 (intern (concat ":" (symbol-name r)))
1284 (lexical-let ((data data))
1288 ;; When r is not an empty string...
1289 (when (and (stringp data)
1290 (< 0 (length data)))
1291 ;; this function is not strictly necessary but I think it
1292 ;; makes the code clearer -tzz
1293 (let ((printer (lambda ()
1294 ;; append the key (the symbol name of r)
1295 ;; and the value in r
1298 (if (zerop (length add)) "" " ")
1299 ;; remap auth-source tokens to netrc
1304 (port "port") ; redundant but clearer
1305 (t (symbol-name r)))
1306 (if (string-match "[\" ]" data)
1309 (setq add (concat add (funcall printer)))))))
1314 (lexical-let ((file file)
1316 (lambda () (auth-source-netrc-saver file add))))
1320 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1321 (defun auth-source-netrc-saver (file add)
1322 "Save a line ADD in FILE, prompting along the way.
1323 Respects `auth-source-save-behavior'. Uses
1324 `auth-source-netrc-cache' to avoid prompting more than once."
1325 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1326 (cached (assoc key auth-source-netrc-cache)))
1329 (auth-source-do-trivia
1330 "auth-source-netrc-saver: found previous run for key %s, returning"
1333 (when (file-exists-p file)
1334 (insert-file-contents file))
1335 (when auth-source-gpg-encrypt-to
1336 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1337 ;; this buffer lets epa-file skip the key selection query
1338 ;; (see the `local-variable-p' check in
1339 ;; `epa-file-write-region').
1340 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1341 (make-local-variable 'epa-file-encrypt-to))
1342 (if (listp auth-source-gpg-encrypt-to)
1343 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1344 ;; we want the new data to be found first, so insert at beginning
1345 (goto-char (point-min))
1347 ;; Ask AFTER we've successfully opened the file.
1348 (let ((prompt (format "Save auth info to file %s? " file))
1349 (done (not (eq auth-source-save-behavior 'ask)))
1350 (bufname "*auth-source Help*")
1353 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1357 (with-output-to-temp-buffer bufname
1359 (concat "(y)es, save\n"
1360 "(n)o but use the info\n"
1361 "(N)o and don't ask to save again\n"
1363 "(?) for help as you can see.\n"))
1364 ;; Why? Doesn't with-output-to-temp-buffer already do
1365 ;; the exact same thing anyway? --Stef
1366 (set-buffer standard-output)
1373 (customize-save-variable 'auth-source-save-behavior nil))
1374 (?e (setq add (read-string "Line to add: " add)))
1377 (when (get-buffer-window bufname)
1378 (delete-window (get-buffer-window bufname)))
1380 ;; Make sure the info is not saved.
1381 (when (null auth-source-save-behavior)
1384 (when (< 0 (length add))
1389 (write-region (point-min) (point-max) file nil 'silent)
1390 ;; Make the .authinfo file non-world-readable.
1391 (set-file-modes file #o600)
1392 (auth-source-do-debug
1393 "auth-source-netrc-create: wrote 1 new line to %s"
1395 (message "Saved new authentication information to %s" file)
1397 (aput 'auth-source-netrc-cache key "ran"))))
1399 ;;; Backend specific parsing: Secrets API backend
1401 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1402 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1403 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1404 ;;; (let ((auth-sources '(default))) (auth-source-search))
1405 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1406 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1408 (defun* auth-source-secrets-search (&rest
1410 &key backend create delete label
1411 type max host user port
1413 "Search the Secrets API; spec is like `auth-source'.
1415 The :label key specifies the item's label. It is the only key
1416 that can specify a substring. Any :label value besides a string
1417 will allow any label.
1419 All other search keys must match exactly. If you need substring
1420 matching, do a wider search and narrow it down yourself.
1422 You'll get back all the properties of the token as a plist.
1424 Here's an example that looks for the first item in the 'Login'
1427 \(let ((auth-sources '(\"secrets:Login\")))
1428 (auth-source-search :max 1)
1430 Here's another that looks for the first item in the 'Login'
1431 Secrets collection whose label contains 'gnus':
1433 \(let ((auth-sources '(\"secrets:Login\")))
1434 (auth-source-search :max 1 :label \"gnus\")
1436 And this one looks for the first item in the 'Login' Secrets
1437 collection that's a Google Chrome entry for the git.gnus.org site
1438 authentication tokens:
1440 \(let ((auth-sources '(\"secrets:Login\")))
1441 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1445 (assert (not create) nil
1446 "The Secrets API auth-source backend doesn't support creation yet")
1448 ;; (secrets-delete-item coll elt)
1449 (assert (not delete) nil
1450 "The Secrets API auth-source backend doesn't support deletion yet")
1452 (let* ((coll (oref backend source))
1453 (max (or max 5000)) ; sanity check: default to stop at 5K
1454 (ignored-keys '(:create :delete :max :backend :label))
1455 (search-keys (loop for i below (length spec) by 2
1456 unless (memq (nth i spec) ignored-keys)
1457 collect (nth i spec)))
1458 ;; build a search spec without the ignored keys
1459 ;; if a search key is nil or t (match anything), we skip it
1460 (search-spec (apply 'append (mapcar
1462 (if (or (null (plist-get spec k))
1463 (eq t (plist-get spec k)))
1465 (list k (plist-get spec k))))
1467 ;; needed keys (always including host, login, port, and secret)
1468 (returned-keys (mm-delete-duplicates (append
1469 '(:host :login :port :secret)
1471 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1472 unless (and (stringp label)
1473 (not (string-match label item)))
1475 ;; TODO: respect max in `secrets-search-items', not after the fact
1476 (items (butlast items (- (length items) max)))
1477 ;; convert the item name to a full plist
1478 (items (mapcar (lambda (item)
1480 ;; make an entry for the secret (password) element
1483 (lexical-let ((v (secrets-get-secret coll item)))
1485 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1487 (mapcar (lambda (entry)
1488 (list (car entry) (cdr entry)))
1489 (secrets-get-attributes coll item)))))
1491 ;; ensure each item has each key in `returned-keys'
1492 (items (mapcar (lambda (plist)
1495 (mapcar (lambda (req)
1496 (if (plist-get plist req)
1504 (defun* auth-source-secrets-create (&rest
1506 &key backend type max host user port
1509 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1512 ;;; Backend specific parsing: PLSTORE backend
1514 (defun* auth-source-plstore-search (&rest
1516 &key backend create delete label
1517 type max host user port
1519 "Search the PLSTORE; spec is like `auth-source'."
1520 (let* ((store (oref backend data))
1521 (max (or max 5000)) ; sanity check: default to stop at 5K
1522 (ignored-keys '(:create :delete :max :backend :require))
1523 (search-keys (loop for i below (length spec) by 2
1524 unless (memq (nth i spec) ignored-keys)
1525 collect (nth i spec)))
1526 ;; build a search spec without the ignored keys
1527 ;; if a search key is nil or t (match anything), we skip it
1528 (search-spec (apply 'append (mapcar
1530 (let ((v (plist-get spec k)))
1538 ;; needed keys (always including host, login, port, and secret)
1539 (returned-keys (mm-delete-duplicates (append
1540 '(:host :login :port :secret)
1542 (items (plstore-find store search-spec))
1543 (item-names (mapcar #'car items))
1544 (items (butlast items (- (length items) max)))
1545 ;; convert the item to a full plist
1546 (items (mapcar (lambda (item)
1547 (let* ((plist (copy-tree (cdr item)))
1548 (secret (plist-member plist :secret)))
1552 (lexical-let ((v (car (cdr secret))))
1556 ;; ensure each item has each key in `returned-keys'
1557 (items (mapcar (lambda (plist)
1560 (mapcar (lambda (req)
1561 (if (plist-get plist req)
1568 ;; if we need to create an entry AND none were found to match
1572 ;; create based on the spec and record the value
1574 ;; if the user did not want to create the entry
1575 ;; in the file, it will be returned
1576 (apply (slot-value backend 'create-function) spec)
1577 ;; if not, we do the search again without :create
1578 ;; to get the updated data.
1580 ;; the result will be returned, even if the search fails
1581 (apply 'auth-source-plstore-search
1582 (plist-put spec :create nil)))))
1585 (dolist (item-name item-names)
1586 (plstore-delete store item-name))
1587 (plstore-save store)))
1590 (defun* auth-source-plstore-create (&rest spec
1592 secret host user port create
1594 (let* ((base-required '(host user port secret))
1595 (base-secret '(secret))
1596 ;; we know (because of an assertion in auth-source-search) that the
1597 ;; :create parameter is either t or a list (which includes nil)
1598 (create-extra (if (eq t create) nil create))
1599 (current-data (car (auth-source-search :max 1
1602 (required (append base-required create-extra))
1603 (file (oref backend source))
1605 ;; `valist' is an alist
1607 ;; `artificial' will be returned if no creation is needed
1611 ;; only for base required elements (defined as function parameters):
1612 ;; fill in the valist with whatever data we may have from the search
1613 ;; we complete the first value if it's a list and use the value otherwise
1614 (dolist (br base-required)
1615 (when (symbol-value br)
1616 (let ((br-choice (cond
1617 ;; all-accepting choice (predicate is t)
1618 ((eq t (symbol-value br)) nil)
1619 ;; just the value otherwise
1620 (t (symbol-value br)))))
1622 (aput 'valist br br-choice)))))
1624 ;; for extra required elements, see if the spec includes a value for them
1625 (dolist (er create-extra)
1626 (let ((name (concat ":" (symbol-name er)))
1627 (keys (loop for i below (length spec) by 2
1628 collect (nth i spec))))
1630 (when (equal (symbol-name k) name)
1631 (aput 'valist er (plist-get spec k))))))
1633 ;; for each required element
1634 (dolist (r required)
1635 (let* ((data (aget valist r))
1636 ;; take the first element if the data is a list
1637 (data (or (auth-source-netrc-element-or-first data)
1638 (plist-get current-data
1639 (intern (format ":%s" r) obarray))))
1640 ;; this is the default to be offered
1641 (given-default (aget auth-source-creation-defaults r))
1642 ;; the default supplementals are simple:
1643 ;; for the user, try `given-default' and then (user-login-name);
1644 ;; otherwise take `given-default'
1646 ((and (not given-default) (eq r 'user))
1649 (printable-defaults (list
1652 (auth-source-netrc-element-or-first
1653 (aget valist 'user))
1654 (plist-get artificial :user)
1658 (auth-source-netrc-element-or-first
1659 (aget valist 'host))
1660 (plist-get artificial :host)
1664 (auth-source-netrc-element-or-first
1665 (aget valist 'port))
1666 (plist-get artificial :port)
1668 (prompt (or (aget auth-source-creation-prompts r)
1670 (secret "%p password for %u@%h: ")
1671 (user "%p user name for %h: ")
1672 (host "%p host name for user %u: ")
1673 (port "%p port for %u@%h: "))
1674 (format "Enter %s (%%u@%%h:%%p): " r)))
1675 (prompt (auth-source-format-prompt
1677 `((?u ,(aget printable-defaults 'user))
1678 (?h ,(aget printable-defaults 'host))
1679 (?p ,(aget printable-defaults 'port))))))
1681 ;; Store the data, prompting for the password if needed.
1684 (or (eval default) (read-passwd prompt))
1685 (if (stringp default)
1686 (read-string (if (string-match ": *\\'" prompt)
1687 (concat (substring prompt 0 (match-beginning 0))
1688 " (default " default "): ")
1689 (concat prompt "(default " default ") "))
1694 (if (member r base-secret)
1695 (setq secret-artificial
1696 (plist-put secret-artificial
1697 (intern (concat ":" (symbol-name r)))
1699 (setq artificial (plist-put artificial
1700 (intern (concat ":" (symbol-name r)))
1702 (plstore-put (oref backend data)
1703 (sha1 (format "%s@%s:%s"
1704 (plist-get artificial :user)
1705 (plist-get artificial :host)
1706 (plist-get artificial :port)))
1707 artificial secret-artificial)
1708 (if (y-or-n-p (format "Save auth info to file %s? "
1709 (plstore-get-file (oref backend data))))
1710 (plstore-save (oref backend data)))))
1714 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1716 ;; deprecate the old interface
1717 (make-obsolete 'auth-source-user-or-password
1718 'auth-source-search "Emacs 24.1")
1719 (make-obsolete 'auth-source-forget-user-or-password
1720 'auth-source-forget "Emacs 24.1")
1722 (defun auth-source-user-or-password
1723 (mode host port &optional username create-missing delete-existing)
1724 "Find MODE (string or list of strings) matching HOST and PORT.
1726 DEPRECATED in favor of `auth-source-search'!
1728 USERNAME is optional and will be used as \"login\" in a search
1729 across the Secret Service API (see secrets.el) if the resulting
1730 items don't have a username. This means that if you search for
1731 username \"joe\" and it matches an item but the item doesn't have
1732 a :user attribute, the username \"joe\" will be returned.
1734 A non nil DELETE-EXISTING means deleting any matching password
1735 entry in the respective sources. This is useful only when
1736 CREATE-MISSING is non nil as well; the intended use case is to
1737 remove wrong password entries.
1739 If no matching entry is found, and CREATE-MISSING is non nil,
1740 the password will be retrieved interactively, and it will be
1741 stored in the password database which matches best (see
1744 MODE can be \"login\" or \"password\"."
1745 (auth-source-do-debug
1746 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1747 mode host port username)
1749 (let* ((listy (listp mode))
1750 (mode (if listy mode (list mode)))
1752 (format "%s %s:%s %s" mode host port username)
1753 (format "%s %s:%s" mode host port)))
1754 (search (list :host host :port port))
1755 (search (if username (append search (list :user username)) search))
1756 (search (if create-missing
1757 (append search (list :create t))
1759 (search (if delete-existing
1760 (append search (list :delete t))
1762 ;; (found (if (not delete-existing)
1763 ;; (gethash cname auth-source-cache)
1764 ;; (remhash cname auth-source-cache)
1769 (auth-source-do-debug
1770 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1772 ;; don't show the password
1773 (if (and (member "password" mode) t)
1777 found) ; return the found data
1778 ;; else, if not found, search with a max of 1
1779 (let ((choice (nth 0 (apply 'auth-source-search
1780 (append '(:max 1) search)))))
1784 ((equal "password" m)
1785 (push (if (plist-get choice :secret)
1786 (funcall (plist-get choice :secret))
1789 (push (plist-get choice :user) found)))))
1790 (setq found (nreverse found))
1791 (setq found (if listy found (car-safe found)))))
1795 (defun auth-source-user-and-password (host &optional user)
1796 (let* ((auth-info (car
1800 :user "yourusername"
1802 :require '(:user :secret)
1807 :require '(:user :secret)
1809 (user (plist-get auth-info :user))
1810 (password (plist-get auth-info :secret)))
1811 (when (functionp password)
1812 (setq password (funcall password)))
1813 (list user password auth-info)))
1815 (provide 'auth-source)
1817 ;;; auth-source.el ends here